+ 2

Virtual keyword in cpp

Why we use virtual keyword in multiple inheritance in cpp?? What is the exact role of virtual keyword in inheritance?

5th Mar 2020, 4:47 PM
Sanchay Kumar
Sanchay Kumar - avatar
3 Answers
+ 3
Sanchay Kumar , let me give you example : #include <iostream> using namespace std; class Man { public: virtual void display() { cout << "I am man" << endl; } }; class Father : public Man { public: void display() { cout << "I am father" << endl; } }; int main() { Man* pMan; pMan = new Man(); pMan->display(); pMan = new Father(); pMan->display(); return 0; } Run above code as it is and check what is output.. Now, remove virtual keyword and again check the output... You would see that results differ.. this is use of virtual keyword... Feel free to ask for any doubts...
5th Mar 2020, 7:24 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
Thank u soo much
6th Mar 2020, 8:04 AM
Sanchay Kumar
Sanchay Kumar - avatar
+ 1
Good to know that it helped...
6th Mar 2020, 6:20 PM
Ketan Lalcheta
Ketan Lalcheta - avatar