Like Java and C#, can I create object of a class within the same class?
/* State.h */
class State{
private:
/*...*/
State PrevState;
};
Error:
field 'PrevState' has incomplete type
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You cannot do this as written. When you declare a variable as some type directly in a class (
Type variablename) then the memory for the variable’s allocation becomes part of its parent type’s allocation. Knowing this, it becomes clear why you can’t do this: the allocation would expand recursively —PrevStatewould need to allocate space for it’sPrevStatemember, and so on forever. Further, even if one could allocate an infinite amount of memory this way, the constructor calls would recurse infinitely.You can, however, define a variable that is a reference or pointer to the containing type, either
State &orState *(or some smart pointer type), since these types are of a fixed size (references are usually pointer-sized, and pointers will be either 4 or 8 bytes, depending on your architecture).