Reputation:
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
Upvotes: 1
Views: 337
Reputation: 52365
So why can you do this in C# and Java, but you cannot do this in C++?
In C++, objects can contain sub-objects. What this means is that the memory for the sub-object will be part of the object that contains it. However, in C# and Java, objects cannot have subobjects, when you do State PrevState;
in one of those languages the memory resides somewhere else outside of the container and you are only holding a "reference" to the actual object within the class. To do that in C++, you would use a pointer or reference to the actual object.
Upvotes: 0
Reputation: 146910
You are mistaking State PrevState
and State* PrevState
. The cause of the problem is that you are assuming that C++ is anything, at all like Java and C#. It isn't. You need to spend some time brushing up your C++.
Upvotes: 0
Reputation: 168998
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 -- PrevState
would need to allocate space for it's PrevState
member, 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 &
or State *
(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).
Upvotes: 2