I was given the following code and asked what it prints:
#include <iostream>
using namespace std;
class C;
class B;
class A {
private:
B* pointerB;
C* pointerC;
public:
A(){ cout << "1"<< endl; }
A(C* c1): pointerC(c1){ cout << "2"<< endl; }
A(const A& a): pointerC(a.pointerC){ cout << "3"<< endl; }
virtual void f() { cout << "4"<< endl; }
void g() { print(); cout<< "5"<< endl; }
virtual void h(){ print(); cout<< "6"<< endl; }
virtual ~A(){ cout << "7"<< endl; }
virtual void print() { cout << "8"<< endl; }
};
class B: public A {
private:
int x;
public:
B(int x1 = 0): x(x1){ cout << "9"<< endl; }
B(const A& a) : A(a), x(2) { cout << "10"<< endl; }
B(const B& b): A(b), x(2) { cout << "11"<< endl; }
virtual void g() { x++; print();}
void f(){ B::print(); cout << "12"<< endl; }
void print() { cout << "13"<< x << endl; }
virtual ~B(){ cout << "14"<< endl; }
};
int main() {
A* ptrAtoB = new B;
B* ptrBtoC = new C;
A* ptrAtoC = new c;
ptrAtoB->f();
ptrAtoB->g();
}
for ptrAtoB->f();
we go to class B and execute B::f() function, which uses B::print() that prints 13, then x=0, then B::f() prints 12.
However, the next line, I expected ptrAtoB->g();
to do the same, meaning go using B class functions to print 13 1 since we use B::g() to raise x to 1, then print.
What ends up happening is that we go to A::g() first, then somehow that uses B::print() to print 13 0, and then back to A::g() to print 5.
why is that?
the final output on console is :
130
12
130
5