Virtual functions in derived classes
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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
Recommended Posts:
- Can static functions be virtual in C++?
- Virtual Destructor
- Catching base and derived classes as exceptions
- Nested Classes in C++
- Functions that cannot be overloaded in C++
- Some interesting facts about static member functions in C++
- Advanced C++ | Virtual Constructor
- Local Classes in C++
- Advanced C++ | Virtual Copy Constructor
- Pure Functions
- Default arguments and virtual function
- What happens when more restrictive access is given to a derived class method in C++?
- Can virtual functions be private in C++?
- Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
- Can virtual functions be inlined?

