Virtual Functions

  • + 0 comments
    // class Person --> Main class 
    class Person {
        public :
        int age;
        string name;
        virtual void getdata()=0;   // actually pure virtual functions 
        virtual void putdata() =0;  
    };
    // class Professor
    class Professor: public Person{
        public :
        int publications;
       static int cur_id;   // 
       int temp_id;    // for storing cur_id and assigning it then ++ 
        //constructor to ++ the cur id
        Professor(){temp_id=++cur_id; }
        void getdata();
        void putdata();
    };
    int Professor::cur_id=0;
    
    // basically check the input and output and try to understan what's going on , then you can understand that " 1/2 is for either professor/student , but in o/p cur_id will also 1/2 is for because we have to initialize a static var. for each class starting from 0 ,  and will be ++ as per input -----> for all this we have to use a constructor which will automatically ++ that , if that class object is created . "
    
    void Professor::getdata(){
        cin>>name>>age>>publications;
    }
    
    // 
    void Professor::putdata(){
        cout<<name<<" "<<age<<" "<<publications<<" "<<temp_id<<endl;
    }
    
    // NOW STUDENT CLASS
    class Student: public Person{
        public :
        int marks[6];
        static int cur_id;
        int temp_id;
        // same explanation check upper 
        Student(){
            temp_id=++cur_id;
        }
        
        void getdata();
        void putdata(); 
    };
    
    int Student::cur_id=0;
    // 
    void Student::getdata(){
        //cout<<"taking";
        cin>>name>>age;
        for(int i=0;i<6;i++){
            cin>>marks[i];
        } 
    }
    
    // 
    void Student :: putdata(){
         int total_sum=0;
         for(int i=0;i<6;i++){
            total_sum=total_sum+marks[i];
         }
         cout<<name<<" "<<age<<" "<<total_sum<<" "<<temp_id<<endl;
        
    }