Reputation: 958
I am looking at an example case of the behavior of virtual functions. Given this test code, I have a few questions as to its behavior.
class A
{
public:
A(int x)
{
cout << "In A Constructor" << endl;
print();
}
~A(){
cout << "In A Destructor" << endl;
delete _val;
}
virtual void print() { cout << "A." << endl; }
private:
char* _val;
};
class B: public A
{
public:
B(int x, int y) : A(x)
{
_dVal = new char[y];
cout << "In B Constructor 1" << endl;
print();
}
B() : A(0)
{
_dVal = new char[1];
cout << "In B Constructor 2" << endl;
print();
}
~B(){
cout << "In B Destructor" << endl;
delete _dVal;
}
void print() { cout << "B" << endl; }
private:
char* _dVal;
};
int main(int argc, char** argv) {
A* p1 = new B();
p1->print();
delete p1;
return 0;
}
The output is:
In A Constructor
A.
In B Constructor 2
B
B
In A Destructor
1) Why is print called for class B if class A is the only one denoting it as a virtual function and it is being called by dereference (->)? 2) Why is the destructor for B never being called if the constructor is in fact being called?
Upvotes: 2
Views: 649
Reputation: 172994
1) Why is print called for class B if class A is the only one denoting it as a virtual function and it is being called by dereference (->)?
That's what virtual functions are supposed to do. The pointer p1
is of type A*
but it's pointing to an object of type B
in fact. And this dynamic binding only happens when a derived class is handled using pointer or reference to the base class.
Also note that the overriding function in the derived class is also virtual (whether or not the keyword virtual is used in its declaration).
2) Why is the destructor for B never being called if the constructor is in fact being called?
The destructor of B
is not called because you're not declaring the destructor of base class (i.e. A::~A
) as virtual destructor. The behavior is undefined for this case. The constructor of B
is called because you construct B
explicitly by new B()
.
Upvotes: 4