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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to convert a class to another class type in C++?
- Difference between Base class and Derived class in C++
- Type Conversion in C++
- Type of 'this' pointer in C++
- What is the size_t data type in C?
- Array Type Manipulation in C++
- Bool data type in C++
- Is there any need of "long" data type in C and C++?
- C++ set for user define data type
- C++ program to find the type of the given iterator
- static_cast in C++ | Type Casting operators
- C++ map having key as a user define data type
- reinterpret_cast in C++ | Type Casting operators
- Data Type Ranges and their macros in C++
- Type Inference in C++ (auto and decltype)
- Function overloading and return type
- Type difference of character literals in C and C++
- Catch block and type conversion in C++
- const_cast in C++ | Type Casting operators
- RTTI (Run-time type Information) in C++