Initializing Object

Hi guys, I know this is a stupid question but could someone give me an answer.
I know that this code is illegal
1
2
struct A
{A newA;};

But I do not understand why it is illegal and also
1
2
struct A
{A *newA;};
why is this code completely legal? Thanks.
Last edited on
In the first case, A must contain an A, which will then contain another A, which will then contain another A, and so on. Hopefully you can see why this is a problem.

The second is not, because all you are containing is a pointer to an A, which could point to anything or nothing.
c/c++ is based on basic types, like int (4 bytes), char(1 byte), etc..
1
2
3
4
struct A
{
A newA;
};

is incomplete type. Compiler doesn't has any information about memory size of this custom type (struct A).
To continue on with the explanation...

All pointers are the same size, irrespecitve of their type, for a given processor architecture (e.g. 8 bytes in the 64-bit case.) So the compiler knows how much space it needs to allow for an A* pointer, even though it doesn't know the details of the type, which is enough information for it to work out the memory layout of the overall struct.

It's the same reason why this is not legal

1
2
3
4
5
6
7
8
9
10
11
12
13
class B;

B b; // incomplete type

struct A
{
    B b; // incomplete type
};

class B
{
    // whatever...
};


but this is

1
2
3
4
5
6
7
8
9
10
11
12
13
class B;

B* pb;

struct A
{
    B* pb;
};

class B
{
    // whatever...
};


(Of course, you can't use pb until after the compiler know the details of struct B.)

Andy
Last edited on
Thanks for the reply everyone, helped a lot.
Topic archived. No new replies allowed.