Thursday, 14 August 2014

can we create a objects of same type for the class?

No comments:

Can we create a object of same type for the class?


class fruit
    // fruit f; Not possible
    static fruit f; // Not part of class objects memory
    fruit *fp;
    fruit &fr;

int main()
    fruit apple;

No is is not possible at all.

Why class cannot data member object of self type?

The class cannot have the data member of self type. Because the size of the data member object was not known at the compile time. say suppose one int and self type in the class

32-bit machine

class fruit
    int a;// 4 bytes
    fruit f;// 4+ sizeof(fruit);

Now the size of the fruit object declared inside the class can be found using the following formula


What will be the result of sizeof(fruit) value?

It is combination of a int variable and fruit object f.

This loops continuosly as mentioned below

4 + sizeof( 4 + sizeof( 4+ sizeof(4 + sizeof(..................))))


So why pointer and reference objects are allowed?

It is allowed because its size is known. By defauly pointer size is common to all kinds of classes. So we need to worry and stack allocates the memory without any trouble.

No comments:

Post a Comment