1

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
4
  • 5
    You can't do that. The best you can do is State *PrevState;. Commented Jul 25, 2012 at 2:57
  • 2
    Such an object requires an infinite amount of memory and an infinite amount of time to initialize. Commented Jul 25, 2012 at 2:59
  • 2
    If you are familiar with C#, the code above is closer to public struct State { public State nextState; }. C++ is a language with value semantics, you have to explicitly request reference semantics (by means of pointers/references) Commented Jul 25, 2012 at 3:05
  • Related - stackoverflow.com/questions/8517609/… Commented Jul 25, 2012 at 3:18

3 Answers 3

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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++.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.