Reputation: 5146
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;
}
Upvotes: 0
Views: 163
Reputation: 3911
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;
}
Upvotes: 1
Reputation: 875
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
Upvotes: 1