Pages

Friday, May 14, 2010

C++ questions: Part 8




Q. Why the size of empty Class is one byte?
Ans:
Yes, the compiler will generate 1 byte of memory to mark the existence of the class.  This doesn't answer WHY though.  The reason is the language standard states that all classes must have a memory size of at least 1 byte so that the class doesn't occupy the same memory space with another class.  This is to prevent name mangling.  i.e., if I declare a class A {};, the compiler will still generate an entry in its table to something called "A".  If behind that I declare another class, say class B, if A takes 0 bytes of memory, and B's data gets written in the place where A was declared.  In this case, an instantiation of A would take on the properties of B. 

Q. What are the default methods of every object?
Ans:
http://qiang-ma.blogspot.com/2007/06/c-default-methods.html
 +---------------------------------------------------------+
|What Name |
+---------------------------------------------------------+
|Default Constructor A::A() |
|Copy Constructor A::A(const A &) |
|Assignment [const] A &A::operator=(const A &) |
|Destructor A::~A() |
+---------------------------------------------------------+


Q. Why a constructor can't be virtual?
Ans:

A constructor can not be virtual because at the time when the constructor is invoked the virtual table (vtable) would not be available in the memory.

Virtual allows us to call a function knowing only the interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know the what you want to create exactly. Hence call to a constructor can't be virtual.