Loay Loay - 1 year ago 113
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{

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

in which the output is :


Does this mean the type of
pointer passed to constructor
is of type

Answer Source


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download