NetApp Interview Question
Software Engineer / DevelopersCountry: United States
Since it's a normal function, address of the function would be somewhere in the code section of your program. This location is the same for all instances of the class. In fact, it has got nothing to do with the instantiation of object. Because the function would be same across all the objects of the same class.
For a normal member function storage isn't required since the address is known at compile time (or, at the latest, at link time); it therefore doesn't have to be stored separately at runtime.
For virtual functions, the situation is different. Virtual function pointers are stored in an array (called “virtual function-pointer table” or “vtable” for short). Each class has one such vtable and each instance to a class stores a pointer to that vtable. This is necessary because if a pointer/reference of type Base points to a sub-class Derived, the compiler has no way of knowing which function to call; rather, the correct function is calculated at runtime by looking it up in the associated vtable. The vtable pointer is also evident in the sizeof the object.
When an object is created as above then only data members size is required(in certain cases like in case of virtual function some more size may be required as for VPTR)....all objects of the class use the same code which is stored at some location and so function's code is related to CLASS and not to OBJECT.
First of all this is not a valid code and will end up in compilation error;
- bibhay.vishesh August 01, 2011The valid code(which i assume that the person who asked the question intended) is
class A {
int a;
void show(){ };
};
int main()
{
A * obj = new A();
printf("\n object size = %d", sizeof(A));
return 0;
}