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.
#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; } |
chevron_right
filter_none
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Pure Virtual Functions and Abstract Classes in C++
- Catching base and derived classes as exceptions
- Can virtual functions be private in C++?
- Can virtual functions be inlined?
- Can static functions be virtual in C++?
- Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
- Derived Data Types in C++
- What happens when more restrictive access is given to a derived class method in C++?
- What happens when a virtual function is called inside a non-virtual function in C++
- Difference between Virtual function and Pure virtual function in C++
- Difference between Base class and Derived class in C++
- Difference between fundamental data types and derived data types
- Virtual Destructor
- Virtual Function in C++
- Virtual destruction using shared_ptr in C++
- Advanced C++ | Virtual Constructor
- Pure virtual destructor in C++
- Virtual base class in C++
- Default arguments and virtual function
- Advanced C++ | Virtual Copy Constructor

