Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling global function from constructor

Tags:

c++

oop

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

like image 609
Loay Avatar asked Sep 06 '16 12:09

Loay


2 Answers

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

like image 82
Hayt Avatar answered Nov 02 '22 06:11

Hayt


As mentioned in [9.2.2.1/1] of the working draft (the this pointer):

The type of this in a member function of a class X is X*.

Note that the constructor is a special member function and A is a subobject of B, thus the this pointer within the body of the member functions of A is of type A*, while it is of type B* within the member functions of B.
Note also that the this from A and the this from B can also have different values, that is they can point to different subobjects.
As an example:

#include<iostream>

struct A {
    A() { std::cout << this << std::endl; }
    int i{0};
};

struct B: A {
    B() { std::cout << this << std::endl; }
    virtual void f() {}
};

int main() {
    B b;
}

That said:

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

No, it isn't. It's of type A*.


EDIT

Despite the OP edited the question and changed its meaning, I'd rather leave in this answer the quote from the original question.
A rollback would be a proper action for that edit maybe.
Anyway, the answer still applies.

like image 8
skypjack Avatar answered Nov 02 '22 06:11

skypjack