-1

Possible Duplicate:
C++ - Forward declaration

so in my header file i have a class defined/declared with all it features named User

then in a .cpp source file there is near the top class User;

im new to c, but couldnt find an answer in the few tutorials i looked into so came here

what does it do ?

thankyou.

Community
  • 1
  • 1
Hayden Thring
  • 1,718
  • 17
  • 25

3 Answers3

2

It's called a forward declaration and enables the compiler to recognise the class without actually knowing its internals. You just inform the compiler that such a class exists, and declaring a pointer to it will not raise an error.

The alternative would be to include the corresponding header file that declares the class, but that would be way too heavy if all you need is having pointers to that type.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
  • ok great, so do you need to do this at the top of each cpp file you will be referencing that class in ? – Hayden Thring Oct 16 '12 at 08:21
  • No you don't have to do this. As the answerer said, you can also include the header file, that has the declaration of the class. When you reference an object like `MyClass thisIsMyClass` then the compiler needs to know the size of MyClass and thus a forward declaration won't fit, but if you use a pointer to the class like `MyClass* pThisIsMyClass` then the compiler just needs to know that an object named `MyClass` is defined somewhere and then you can use either a forward declaration or an include of the header. – AquilaRapax Oct 16 '12 at 08:30
1

It is a so called "Forward declaration": it makes the class known to the compiler, without actually defining it. Note that this is C++, not C.

Ralph
  • 5,154
  • 1
  • 21
  • 19
0

It declares the class without actually defining it. In that sense, it's no different to:

void doSomething(void);

That prototype tells the compiler that doSomething() exists but doesn't actually specify what it does.

It's generally used where you need the class to exist (so you can reference it somehow) but you don't need to know anything about its properties.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953