dynamic binding and this pointer

R

rong

Hi,

I have some puzzle on what "this" pointer really points in
constructor, in particular in the case of inheritance - explained in
the following sample


#include <iostream>
#include <string>

using namespace std;

class Base;
static string getType(Base *p);

class Base {
public:
Base() { cout << "Type: " << getType(this) << endl; }
void showType() { cout << "Type: " << getType(this) << endl; }

virtual string type() { return string("Base"); }
};

class Derived : public Base {
public:
string type() { return string("Derived"); }
};

static string getType(Base *p)
{
return p->type();
}

int main(int argc, char **argv)
{
Derived foo;

foo.showType();
return 0;
}


I was expecting both lines printed should be "Type: Derived", but it
actually prints out

Type: Base
Type: Derived

Any idea? Thanks.


Regards,

Rong
 
J

joshuamaurice

Hi,

I have some puzzle on what "this" pointer really points in
constructor, in particular in the case of inheritance - explained in
the following sample

#include <iostream>
#include <string>

using namespace std;

class Base;
static string getType(Base *p);

class Base {
public:
        Base() { cout << "Type: " << getType(this) << endl; }
        void showType() { cout << "Type: " << getType(this) << endl; }

        virtual string type() { return string("Base"); }

};

class Derived : public Base {
public:
         string type() { return string("Derived"); }

};

static string getType(Base *p)
{
        return p->type();

}

int main(int argc, char **argv)
{
        Derived foo;

        foo.showType();
        return 0;

}

I was expecting both lines printed should be "Type: Derived", but it
actually prints out

Type: Base
Type: Derived

Any idea? Thanks.

Short answer: because the standard says so. The this object does not
point to a derived object until it enters the derived constructor.

The rationale is that if a base constructor called a virtual function,
and this resolved to the implementation in the derived class, then
this will access an object which has not been constructed. It will not
be set up, constructors for member sub objects of the derived object
will not be called. The derived object is in a garbage state until the
derived constructor is called, so that's why it's done this way.

I reasonably sure that the same thing happens for destructors too.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top