(C++) How can I get the size of an object from a pointer to a base class?
class Class{
public:
int Something;
};
class DerClass : public Class{
public:
int Array[256];
};
main()
{
Class*C = new DerClass;
sizeof(*C); // = 4
sizeof(DerClass); // = 1028
}
// How can I get 1028 from pointer C?
(C++) How can I get the size of an object from a pointer to a base class?c++ compiler
As far as I know, in c++ it is impossible to get the size of an object just from the base class and sizeof function. One way to get around this is to use dynamic_cast as follows.
struct A {
int a;
virtual ~A() {}
};
struct B : public A {
int b[128];
virtual ~B() {}
};
struct C : public A {
int c[256];
virtual ~C() {}
};
size_t sizeofA(A* a) {
if (dynamic_cast<C*>(a))
return sizeof(C);
else if (dynamic_cast<B*>(a))
return sizeof(B);
else
return sizeof(A);
}
(C++) How can I get the size of an object from a pointer to a base class?c++ cli
sizeof() hard codes size of objects into the program at compile time. Allocated (ie: 'new') memory block sizes are unknown until run time, making sizeof() hopeless to help.
So, don't think it can be done via pointer.
More Related Questions and Answers ...
The information post by website user , we not guarantee correctness.
Dental Treatment Skin Whitening Skin Problems Skin Rashes Shoes
