A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type.
For example, following program works fine.
And following program also works fine.
But following program generates compilation error “field `self’ has incomplete type”
If a non-static object is member then declaration of class is incomplete and compiler has no way to find out size of the objects of the class.
Static variables do not contribute to the size of objects. So no problem in calculating size with static variables of self type.
For a compiler, all pointers have a fixed size irrespective of the data type they are pointing to, so no problem with this also.
Thanks to Manish Jain and Venki for their contribution to this post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- What all is inherited from parent class in C++?
- Data type of character constants in C and C++
- RTTI (Run-time type Information) in C++
- Type difference of character literals in C and C++
- Function overloading and return type
- Structure vs class in C++
- Type of 'this' pointer in C++
- Hiding of all overloaded methods with same name in base class
- Why is the size of an empty class not zero in C++?
- Exception handling and object destruction | Set 1
- Catch block and type conversion in C++
- Simulating final class in C++
- const_cast in C++ | Type Casting operators
- What happens when more restrictive access is given to a derived class method in C++?
- How to make a C++ class whose objects can only be dynamically allocated?