I have the following code snippet:
#include <iostream>
#include <typeinfo>
using namespace std;
class A{
public:
int x;
A(int i = 0): x(i) {}
A minus(){
return 1 - x;
}
virtual void print(){
cout << x << "\n";
cout << "Base print\n";
}
};
class B: public A{
int y;
public:
B(int i = 0) {x = i;}
void print(){
cout << x << "\n";
cout << "Derived print!\n";
}
};
int main(){
A* p1 = new B(18);
*p1 = p1->minus();
p1->print();
return 0;
}
The output is:
-17
Derived print!
I know where -17
comes from. It does upcasting and A* p1 = new B(18)
and makes p1
point to a derived object with x value of 18. *p1 = p1->minus
make the object that p1
points to be an A(-17) /// cause 1 -18 = -17
. My question is, where does the second line come from ? If p1 points to an A
object after the *p1 = p1->minus()
, why does p1->print()
not print "Base print"
?