Reputation: 1381
Hey I am just trying to figure out the concept of using base class pointer to call methods of derived class, but then I came across this problem.
#include <iostream>
using namespace std;
class A {
int a;
public:
A() {}
A(int x) :a(x) {}
void show() {
cout<<"Hi this is base class ::\nvalue of a is "<<a<<endl;
}
};
class B:public A {
int b;
public:
B() {}
B(int x) : b(x) {}
void show() {
cout<<"Hi this is derived class::\n value of b is "<<b<<endl;
}
};
int main() {
A a(20), *a_ptr;
B b(10), *b_ptr;
a_ptr = &b;
a.show();
a_ptr->show();
return 0;
}
a.show()
outputs:
Hi this is base class ::
value of a is 20
as accepted but
a_ptr->show()
outputs garbage value
Hi this is base class ::
value of a is -1121246592
Can anybody explain why this is happening..
Upvotes: 0
Views: 905
Reputation: 15824
In simple you didn't initialize your base class data member when you are calling a derived class constructor so it is showing garbage value; since it will call base class default constructor.
If you change your base class default constructor as follows, you will get expected result.
A():a(10) {}
Upvotes: 0
Reputation: 9356
This is because in order to have polymorphism you have to define show()
as a virtual function, i.e. in class A
:
virtual void show();
As this is not the case in your code the compiler will statically bind the call a_ptr->show();
to class A
implementation of show which prints the member a
which is not initialized by class B
constructor.
Upvotes: 3