I’m confused about an aspect of polymorphism. Please consider the following code:
#include <iostream>
class CBase {
virtual void dummy() {}
};
class CDerived: public CBase {
public:
int a,b,c,d;
CDerived (): a(1),b(2),c(3),d(4) { }
};
int main () {
CBase* pba = new CDerived;
std::cout << "sizeof(CBase) = " << sizeof(CBase) << std::endl; // prints 8
std::cout << "sizeof(CDerived) = " << sizeof(CDerived) << std::endl; // prints 24
std::cout << "sizeof(*pba) = " << sizeof(*pba) << std::endl; // prints 8 (?)
return 0;
}
My question is the following: on the line CBase* pba = new CDerived; an object of CDerived type (24 bytes) is allocated, but as you can see, sizeof(*pba) = 8 bytes. What happened to the other 16 bytes of the CDerived object pointed by pba? I also tried this:
std::cout << "pba->a = " << pba->a << std::endl;
but then got compilation errors, meaning pba really does not point to an object of type CDerived. So what happened here? Memory leak?
sizeofis a compile-time construct. It can’t know the runtime type, so it only considers the compile-time type, which isCBase&.pba->adoesn’t compile for similar reasons: the compile-time type ofpbaisCBase*, andCBasedoesn’t have anamember. This is how static typed languages work. If you want to useCDerivedmembers, you need a variable with typeCDerived(or a reference or pointer to it).However, the
CDerivedobject is still there. You can see that if you convert the pointer to a pointer toCDerived, likedynamic_cast<CDerived*>(pba)->a.