Edit Solved and Reposted as sample program
The scenario was as follows:
The class hierarchy:
class Base
{
public:
virtual void output() = 0;
private:
int a;
};
class Derived_1 : public Base
{
public:
virtual void output()
{
cout << "Derived_1" << endl;
}
};
class Derived_2 : public Derived_1
{
public:
virtual void output()
{
cout << "Derived_2" << endl;
}
};
The implementation:
Derived_2* obj = reinterpret_cast<Derived_2*>(new Derived_1());
obj->output();
This will output “Derived_1” and not “Derived_2”. I’m sure this is nothing new to most of you, but it was something I didn’t think about when making some of my factory functions in my application.
You are allocating a
Value_object_dataobject, notValue_object_uint32. The fact that you’re casting it as aValue_object_uint32changes nothing. The actual object’s virtual table has no knowledge ofValue_object_uint32; in its virtual function table, which is constructed at the time of err… construction,formatpoints toValue_object_data‘sformat. Strong-arming the type of pointer which points to the actual object does nothing to fix the situation.Constructors for all base and inherited classes in a given hierarchy are called from the most derived to the root, exactly once for each class. This means, you don’t have to explicitly call the base class constructor. It will be called automatically. If you need to specify which of several base class constructors should be used you can do that too:
Of course, the
Derived(int a)constructor is not required to call theBase(int)constructor. In this case theBase()constructor will be called automatically.