VILLAIN bryan
VILLAIN bryan

Reputation: 751

Simple C++ Declaration Issue

Why is this illegal, and what are some logical alternatives?

// State.h
class State {

public:
int a;
int b;
State z; //  <-- this is this problem

// ... Functions ...

};

Thank you.

Upvotes: 0

Views: 123

Answers (4)

rm5248
rm5248

Reputation: 2645

Since z is a local variable, until you scan the entire State class, you can't know how much storage space you need to have. Since State depends on itself, you will recurse infinitely.

Basically here's what happens in the compiler:

I see a class state.  Okay!
I now see a member variable a.  Okay!  Let's add 4 bytes to the size of our state
I now see a member variable b.  Okay!  Let's add 4 bytes to the size of our state
I now see a State.  Okay!  Let's see, our current size is 4 + 4, 
    now let's add the size of State to that, which is... um... ????

Pointers on the other hand have a size known at compile time(typically 4 bytes, but that depends on your architecture.) That way, when you don't know the size of something, you can always have a pointer to it because the size is not important.

This is what happens in the compiler at that point:

I see a class state.  Okay!
I now see a member variable a.  Okay!  Let's add 4 bytes to the size of our state
I now see a member variable b.  Okay!  Let's add 4 bytes to the size of our state
I now see a State*.  Okay!   Let's add 4 bytes to the size of our state
I now see that class state has ended.  Its size is 4 + 4 + 4 = 12.
I can now do State z;  It will take 12 bytes of space.

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124790

Because, if it were allowed, every time you created an instance of State you would create an instance of State which would then create and instance of State and, well, that one needs a State too, so it creates an instance of State... and so on.

It would also send your compiler into infinite recursion while attempting to figure out sizeof(State). Be nice to your compiler.

Maintain a type of pointer instead and you will be fine. On a side note, does it really make sense for a State to have its own (public) State? I mean, I do love seeing lines of code like the following, but it could get ridiculous...

if(state.z->z->z->z->z->z->z->z == some_state) {
    // we found the right state!
}

If you're attempting to create a singleton, make your constructor private and add a static get_instance function which returns the one and only (static) instance of State.

Upvotes: 7

Brandon
Brandon

Reputation: 39222

Use a State * instead. This lets you end the recursion at some point.

Upvotes: 0

someone_ smiley
someone_ smiley

Reputation: 1066

Illogical because this will end up in infinite number of state z because every instance of z will have another instance of z in it and so on . Pointer State* z is allow as it have no such limitation

Upvotes: 1

Related Questions