Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Virtual functions in derived classes

  • Difficulty Level : Easy
  • Last Updated : 07 Nov, 2019

In C++, once a member function is declared as a virtual function in a base class, it becomes virtual in every class derived from that base class. In other words, it is not necessary to use the keyword virtual in the derived class while declaring redefined versions of the virtual base class function.

For example, the following program prints “C::fun() called” as B::fun() becomes virtual automatically.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




#include<iostream>
  
using namespace std;
  
class A {
  public:
    virtual void fun()
    { cout<<"\n A::fun() called ";}
};
  
class B: public A {
  public
    void fun() 
    { cout<<"\n B::fun() called "; }      
};
  
class C: public B {
  public:
    void fun()
    { cout<<"\n C::fun() called "; }      
};
  
int main()
{
   C c; // An object of class C
   B *b = &c; // A pointer of type B* pointing to c
   b->fun();  // this line prints "C::fun() called"
   getchar();
   return 0;
}

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

My Personal Notes arrow_drop_up
Recommended Articles
Page :