Type of an object changing during construction

Viewed 131

I just discoverd the following behaviour : having an object of type B derived from type A, the final type during the construction of A is A and not B. This can be observed with the following example :

#include <iostream>
#include <typeinfo>

class A
{
    public:
        A() { std::cout << &typeid(*this) << std::endl; }
};

class B : public A
{
    public:
        B() : A() { std::cout << &typeid(*this) << std::endl; }
};

int main()
{
    A a;
    B b;
    return 0;
}

A run of this code (compiled with gcc 4.8.5) is the following :

0x400ae0
0x400ae0
0x400ac0

We can see that the type returned by typeid in A::A() is A and not B, and then the final type changes to become B.

Why ?

Is it possible to know the "real" final type during the construction of the parent class ?

My context is the following :

I have a parent class Resource and several classes inheriting from it. I also have a ResourceManager notified by each creation of a resource, and having to know the final type of the created resource. What I'm doing to avoid duplicated code is the following, but it doesn't work :

class Resource
{
  public:
    Resource() { ResourceManager::notifyCreation(*this); }
    ~Resource() { ResourceManager::notifyDestruction(*this); }
};
class MyResource : public Resource
{
  // I don't have to care to the manager here
};

I know I can do the notification in each constructor/destructor of the children, but it's less robust (possible bug if a resource is instanciated without notification to the manager). Have you any idea for a workaround ?

2 Answers
Related