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