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.
Source: http://www.umsl.edu/~subramaniana/virtual2.html
For example, the following program prints “C::fun() called” as B::fun() becomes virtual automatically.
1 #include<iostream> 2 3 using namespace std; 4 5 class A { 6 public: 7 virtual void fun() 8 { 9 cout<<" A::fun() called "; 10 } 11 }; 12 13 class B: public A 14 { 15 public: 16 void fun() 17 { 18 cout<<" B::fun() called "; 19 } 20 }; 21 22 class C: public B 23 { 24 public: 25 void fun() 26 { 27 cout<<" C::fun() called "; 28 } 29 }; 30 31 int main() 32 { 33 C c; // An object of class C 34 B *b = &c; // A pointer of type B* pointing to c 35 b->fun(); // this line prints "C::fun() called" 36 getchar(); 37 return 0; 38 }
Output: C::fun() called
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 20:24:37