Can a C++ class have an object of self type? Last Updated : 31 Jul, 2018 Comments Improve Suggest changes 85 Likes Like Report 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. CPP // A class can have a static member of self type #include<iostream> using namespace std; class Test { static Test self; // works fine /* other stuff in class*/ }; int main() { Test t; getchar(); return 0; } And following program also works fine. CPP // A class can have a pointer to self type #include<iostream> using namespace std; class Test { Test * self; //works fine /* other stuff in class*/ }; int main() { Test t; getchar(); return 0; } But following program generates compilation error "field `self' has incomplete type" CPP // A class cannot have non-static object(s) of self type. #include<iostream> using namespace std; class Test { Test self; // Error /* other stuff in class*/ }; int main() { Test t; getchar(); return 0; } 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. Create Quiz Comment K kartik Follow 85 Improve K kartik Follow 85 Improve Article Tags : C++ Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like