0

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; } 
4
  • 3
    Can you explain why you would expect the result to be "1"? Commented Oct 2, 2016 at 22:01
  • why do you think the output should be 1 actually? Commented Oct 2, 2016 at 22:02
  • 1
    Keep reading your C++ book, which explains this concept fully. Commented Oct 2, 2016 at 22:02
  • remove virtual keywords and you'll have what you want: 1. Commented Oct 2, 2016 at 22:06

2 Answers 2

1

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; } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.