(C++) How can I get the size of an object from a pointer to a base class?

 Dont Buy Textbooks. Rent 'EM Save 60-80%



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 ...
  • Is this what a C++ pointer is in a nutshell?
  • Pointer to a pointer in C programming?
  • Delete pointer in c++?
  • Can any one send me the few practice examples..
  • C problem, function & pointer declaration..
  • C++ >> Object and pointer?
  • Function pointer - C++ code section?
  • Pointer problem in c++ regarding user input?
  • Write Programming in C using pointer (Challen..
  • What is difference between "member selec..
  • C language help regarding Mouse pointer?
  • Can address(&) be used as a pointer in c ..
  • What is meant by Smart Pointer in C++ Languag..
  • How can i manipulate a double pointer in c pr..
  • C++, How do I create a pointer to a class mem..
  • What is pointers...pointer of c++ in oop lang..
  • Diffrence between generic pointer and pointer..
  • What is Pointer in &#039;C&#039;?
  • What is a pointer in C language?

  • The information post by website user , we not guarantee correctness.

    

    Dental Treatment Skin Whitening Skin Problems Skin Rashes Shoes