Sam
Sam

Reputation: 972

Why is it not allowed to define a class object in the same class?

Here is my code:

class Link;
class LinkScreen;
class LinkScreen {
    Link* linkScreen1;
    LinkScreen linkScreen2; 
};

class Link {}; 

The make error:

test.cpp:6:16: error: field ‘linkScreen2’ has incomplete type

Why is this not allowed?

Upvotes: 0

Views: 75

Answers (4)

brokenfoot
brokenfoot

Reputation: 11649

Duplicate: why can't we declare object of a class inside the same class?

Because it requires knowing the size of each of the constituent members of the class linkScreen. In your case size of linkScreen2 is not known, since the class is not completely defined at that very moment.

Upvotes: 1

Wyzard
Wyzard

Reputation: 34573

A class can't contain an instance of itself because that would make the instances take up an infinite amount of space.

Think about it: you create a LinkScreen object… which contains another LinkScreen object… which contains another LinkScreen object, which contains yet another, and so on.

Or, to look at it another way, what's the size of a LinkScreen object? Well, it's the size of the variables it contains: a Link* (typically 4 or 8 bytes) plus the size of a LinkScreen object. But how big is that? Well, it's the size of a Link* plus the size of a LinkScreen. You can see the infinite recursion here.

You can only create an instance of a type that's "complete", which for a class means that the compiler has seen the closing brace of the class definition. That prevents you from putting an instance within the class itself. You can create a pointer to an incomplete type, though; it's OK for a LinkScreen object to contain a LinkScreen* variable.

Upvotes: 4

Adrian Shum
Adrian Shum

Reputation: 40056

Because it is simply illogical:

I suppose you mean LinkScreen * linkScreen2;or LinkScreen& linkScreen2;

If you really want LinkScreen linkScreen2;, then just imagine: A LinkScreen object is going to contain (not referring to) a LinkScreen object, which in turns contain a LinkScreen object..... It is never going to end.


A bit more on having another class as member.

Unlike having pointer/ref to another class, if you want to contain another class as member, having only forward declaration is not enough. Compiler needs to know the actual "layout" of your members, so it can "decide" the "layout of memory" of that class. Therefore you need a complete declaration of the "contained class" available before your class. Which means, it is never going to be possible to have your class "contains" a member of same type.

Upvotes: 0

MTilsted
MTilsted

Reputation: 5543

Your problem is that your LinkScreen object contains a LinkScreen object, which then contain a LinkScreen object which then contain a LinkScreen object and so on. I guess it should be a pointer instead.

Upvotes: 0

Related Questions