Virtual Functions

  • + 0 comments

    This works well on me as an intermediate C++ Programmer with Java basic programming language. The keyword "virtual" is very important.

    int profCount = 0;
    int studentCount = 0;
    
    class Person {
        protected:
        string name;
        int age;
        int id;
        
        public:
        virtual void getdata() {}
        virtual void putdata() {}   
        
    };
    
    class Professor : public Person {
        protected:
        int publications;
        
        public:   
        void getdata() {        
            cin >> this -> name;
            cin >> this -> age;
            cin >> this -> publications;
            profCount++;
            this -> id = profCount;
        } 
        
        void putdata() {
            cout << this -> name << " ";
            cout << this -> age << " ";
            cout << this -> publications << " ";
            cout << this -> id << endl;
        }   
        
    };
    
    class Student : public Person {
        protected:
        int score;
        
        public:   
        void getdata() {        
            cin >> this -> name;
            cin >> this -> age;
            int a, b, c, d, e, f;
            cin >> a >> b >> c >> d >> e >> f;         
            this -> score = a + b + c + d + e + f;
            studentCount++;
            this -> id = studentCount;
        }
        
        void putdata() {
            cout << this -> name << " ";
            cout << this -> age << " ";
            cout << this -> score << " ";
            cout << this -> id << endl;
        }
            
    };