I have two questions related to C++:
In many textbooks, the keyword this
is a pointer to the calling object. Correct?
As i like to play with coding, i wrote the following simple code:
struct Base
{
void g();
virtual void f();
};
void Base::f() {
cout << "Base::f()" << endl;
}
void Base::g() {
cout << "Base::g()" << endl;
cout << "sizeof(*this) : " << sizeof(*this) << endl;
this->f();
}
struct Derived : public Base
{
int d;
void f();
};
void Derived::f()
{
cout << "Derived::f()" << endl;
}
int main()
{
Base a;
Derived b;
cout << "sizeof(a) : " << sizeof(a) << endl;
cout << "sizeof(b) : " << sizeof(b) << endl;
a.g();
b.g();
}
The above code produces the following output:
sizeof(a) : 4
sizeof(b) : 8
Base::g()
sizeof(*this) : 4
Base::f()
Base::g()
sizeof(*this) : 4 // why 4 bytes not 8 bytes?????????
Derived::f()
If this
is pointing to the calling object, should the second line of sizeof(*this)
print 8 instead of 4 since the calling object is b
? What actually is happening here? Is this
has been demoted?!!!!
If this
has been demoted to type Base
, how this->f()
invokes the correct function? I am really confused.
void Base::g() {
cout << "Base::g()" << endl;
cout << "sizeof(*this) : " << sizeof(*this) << endl;
this->f();
}
The important distinction that needs to be made is that sizeof
is a compile-time operator, not a runtime operator. The compiler interprets the expression sizeof(*this)
as "the size of the object pointed to by this
", which, in the scope of Base::g
would be an object of type Base
. The compiler will essentially rewrite that statement as this, because it knows that the size of Base
is four bytes:
cout << "sizeof(*this) : " << 4 << endl;
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