Loay Loay - 2 months ago 17
C++ Question

Calling global function from constructor

I have this code:

#include <iostream>
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 :


A


Does this mean the type of
this
pointer passed to constructor
A()
is of type
A*
?

Answer

Yes.

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*.

Comments