zoukankan      html  css  js  c++  java
  • 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.

      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

  • 相关阅读:
    AOP与IOC的概念(即spring的核心)
    Md5密码加密的使用
    all-mobile.js
    config.js
    login.css
    template.css
    index.js
    view.js
    admin.css
    admin.js
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3444054.html
Copyright © 2011-2022 走看看