I have two classes, while B
derives A
.
I created a pointer to A
, is called: a2
. please take a look in my main
function.
What does this line do?
a2 = new B();
Why when I delete a2
, only the destructor of A is activated?
#include <iostream>
using namespace std;
class A {
int num;
public:
A() { cout << "constructor of A\n"; }
void set_num(int new_num) { cout << "set_num of A" << endl; num = new_num; }
void print() { cout << "print of A: "; cout << num << endl; }
~A() { cout << "destructor of A\n"; }
};
class B: public A {
int num;
public:
B() { cout << "constructor of B\n"; }
void set_num(int new_num) { cout << "set_num of B" << endl; num = new_num; }
void print() { cout << "print of B: "; cout << num << endl; }
~B() { cout << "destructor of B\n"; }
};
void main() {
A *a2;
a2 = new B();
delete a2;
}
this is the output:
constructor of A
constructor of B
destructor of A
Each help appreciated!