Consider the following program:
class Base
{
private:
int m_nID;
public:
Base()
{
m_nID = ClassID();
}
// ClassID returns a class-specific ID number
virtual int ClassID() { return 1; }
int GetID() { return m_nID; }
};
class Derived: public Base
{
public:
Derived()
{
}
virtual int ClassID() { return 2; }
};
int main()
{
Derived cDerived;
cout << cDerived.GetID();
return 0;
}
In the above example,The derived id is surprisingly 1 instead of 2.I have already found a similar question regarding the same question here.But what i don't understand is that if this is wrong,Then how are we supposed to identify a (derived) class member and use it?I mean suppose i want to dedicate a unique id or typename to each class (base class, the first derived class , the second derived class which is either a derivation of the base class or the second derived class and so on),In this regard how can i go on and act? I think the correct way is that i assign an id/name in the constructor upon the instantiation of any class object so that the type is known immediately.The above approach failes,What other options do i have in this regard?