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
jogojapan
  • 68,383
  • 11
  • 101
  • 131
  • 5
    You can't do that. The best you can do is `State *PrevState;`. – Mysticial Jul 25 '12 at 02:57
  • 2
    Such an object requires an infinite amount of memory and an infinite amount of time to initialize. – porges Jul 25 '12 at 02: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) – David Rodríguez - dribeas Jul 25 '12 at 03:05
  • Related - http://stackoverflow.com/questions/8517609/why-is-a-class-allowed-to-have-a-static-member-of-itself-but-not-a-non-static-m/8517644#8517644 – Luchian Grigore Jul 25 '12 at 03:18

3 Answers3

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

cdhowie
  • 158,093
  • 24
  • 286
  • 300
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++.

Puppy
  • 144,682
  • 38
  • 256
  • 465
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.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166