简体   繁体   中英

concept of virtual functions in c++

I am trying to understand the concept of virtual function in C++ and I read it online but I am not able to understand why the below program output is 2 instead of 1? Can anyone explain?

Class A 
{ 
   int a; 
   public: 
       A() 
       {
          a = 1; 
       } 
       virtual void show() 
       { 
          cout <<a;
       } 
};

Class B: public A 
{ 
   int b; 
   public: 
       B() 
       { 
          b = 2; 
       }
       virtual void show() 
       { 
          cout <<b;
       }
};

int main() 
{ 
   A *pA; 
   B oB; 
   pA = &oB; 
   pA->show(); 
   return 0; 
}

From cppreference

Virtual functions are member functions whose behavior can be overridden in derived classes. As opposed to non-virtual functions, the overridden behavior is preserved even if there is no compile-time information about the actual type of the class. If a derived class is handled using pointer or reference to the base class, a call to an overridden virtual function would invoke the behavior defined in the derived class. This behavior is suppressed if the function is selected using qualified name lookup (that is, if the function's name appears to the right of the scope resolution operator ::)

Since, you are overriding show() in class B , pA->show() will call show() in class B .
Hope this helps

you achieve polymorphism with overriding virtual functions and pointers: in your example you used pA polymorphically so it is a pointer to a base class (A) but you but you assign to it a class B's object which is child of A. and you you declared Show() as virtual.

this is the main goal of polymorphis; which means we don't know the type of object the base pointer points to until runtime eg in main:

int main() 
{ 

   int choice;
   cout << "1: A object   2: B object:\n\n";
   cin >> choice;
   if(1 == choice)
       pA = new A; // result will be 1
   else
       if(2 == choice)
           pA = new B; // result will be 2

    if(pA)
        pA->show();
    delete pA;
    pA = NULL;

//  B* pB = new A; // error: cannot convert from class A* to class B* because C++ is not contravariant 
    B* pB = new B;
    pB->show(); // result: 2

    delete pB;
    pB = NULL;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM