Calling global function from constructor

Home - Calling global function from constructor

Girly Saputri Staff asked 10 months ago

I have this code:

#include 
using namespace std;

struct A;
struct B;

void g(A* a){ cout << "A";}
void g(B* b){ cout << "B";}

struct A{
    A(){ g(this); }
};

struct B : A{
    B(){}
};


int main() {
    B* b=new B();
    return 0;
}

in which the output is :

Girly Saputri Staff replied 10 months ago

The thing is a B object is also a A object. While you are inside of the functions of A the class does not know if it is a B or not. So the this-ptr will be of type A*.

When you are calling functions inside of B it is B*.

Your Answer