Initializing Object

Jul 31, 2013 at 9:00am
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 Jul 31, 2013 at 9:02am
Jul 31, 2013 at 9:25am
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.
Jul 31, 2013 at 9:29am
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).
Jul 31, 2013 at 10:33am
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 Jul 31, 2013 at 10:35am
Jul 31, 2013 at 11:33pm
Thanks for the reply everyone, helped a lot.
Topic archived. No new replies allowed.