Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Forward Declaration design

From what i've read, i should use forward declarations whenever I can. I have classes like this ( where every fields are pointers because of forward declarations ) :

class A
{
    // ...

    A* a;
    B* b;
    C* c;
    D* d;
    E* e;
};

But there is problems with that.

1- This implies to call new and delete ( or at least new with smart pointers ) for every fields in constructor, while stack allocated fields don't need this.

2- I've read that stack allocation was faster than heap allocation.

3- Also that means that almost every fields on every classes should be pointers.

Am I doing the right way doing like my example class? Or am I missing something with forward declarations?

like image 514
Aulaulz Avatar asked May 27 '14 08:05

Aulaulz


People also ask

What is a forward declaration C?

As others stated before, a forward declaration in C/C++ is the declaration of something with the actual definition unavailable. Its a declaration telling the compiler "there is a data type ABC".

What do you mean by forward declaration?

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.

Why do we need forward declaration?

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.

What is the purpose of a forward declaration of a class?

A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.


1 Answers

The implication is inverse - you're not supposed to use pointers just in order to use forward declarations, but you're suppose to use forward declarations after you've taken a design decision (such as using pointers instead of objects as members) when you can.

So if it makes more sense to use objects, do so, and include the files you need. Don't use pointers just so you can forward-declare the classes.

like image 156
Luchian Grigore Avatar answered Oct 11 '22 19:10

Luchian Grigore