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*
?
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*
.
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 typeA
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With