BWG
BWG

Reputation: 2298

Uses undefined class/has incomplete type

class a;
class b;

class a {
    b c;
};

class b {
};

Why doesn't this compile? I was under the impression that if you declared prototypes of classes, it didn't matter in which order they were declared. However, this doesn't work. In visual studio, it gives me:

error C2079: 'a::c' uses undefined class 'b'

In g++, it gives me:

error: field 'c' has incomplete type

What am I doing wrong?

Upvotes: 0

Views: 1914

Answers (2)

gturri
gturri

Reputation: 14639

When the compiler sees

class a {
  b c;
};

it knows that b exist, but it doesn't know what it is (hence, it doesn't know how much space it will require, hence it doesn't know how to build a)

However what you could do is using a pointer on b:

class a {
  b* c;
};

Edit:

It means you won't be able to manipulate a b before it is defined. E.g: you can't do:

class a {
  b* c;
  void f(){
    c->doSomething(); // <- Won't compile
  }

};

What you can do is separating a definition in a .hh and .cc:

in a.hh

class b; //Say it exists. Don't say what it looks like

class a {
  b* c;
  void f();
};

in a.cc

#include "b.hh" //now it's ok to use b.hh: it won't yield a circular reference because b.hh may include a.hh but it doesn't include a.cc

void a::f(){
  c->doSomething();
}

Upvotes: 4

David
David

Reputation: 28178

At the time a uses b it has been declared (because you wrote class b; above it) but not defined (the definition is below a). "Incomplete Type" means the type has been declared but not defined.

Upvotes: 0

Related Questions