Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible I have forward declaration of a class, without making them reference or pointer in header file

Tags:

c++

// I prefer to perform forward declaration on myclass, as I do not
// wish to ship "myclass.h" to client
// However, the following code doesn't allow me to do so, as class defination
// is needed in header file.
//
// a.h
#include "myclass.h"
class a {
public:
    a();
    myclass me;
};

I try to do it another way around. However, I need to use dynamic allocation, which I usually try to avoid.

// a.h
class myclass;
class a {
public:
    a();
    myclass& me;
};

// But I just wish to avoid new and delete, is it possible?
// a.cpp
#include "myclass.h"

a::a() : me(*(new myclass())) {
}

a::~a() {
    delete *myclass;
}

Is it possible to do so, without using any reference or pointer? (Or more precisely, without using new/delete)

like image 720
Cheok Yan Cheng Avatar asked Feb 26 '10 02:02

Cheok Yan Cheng


People also ask

Can you forward-declare a class?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). In C++, Forward declarations are usually used for Classes.

Where do you put forward declaration?

Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.

When the forward declaration is required while declaring function?

Forward declaration is used in languages that require declaration before use; it is necessary for mutual recursion in such languages, as it is impossible to define such functions (or data structures) without a forward reference in one definition: one of the functions (respectively, data structures) must be defined ...

Should I use forward declaration or include?

A forward declaration is much faster to parse than a whole header file that itself may include even more header files. Also, if you change something in the header file for class B, everything including that header will have to be recompiled.


1 Answers

No. The reason being, that the compiler needs to know the size of your object (i.e. myclass) in order to know the size of the object (i.e. class "a" in your example). If you have only forward declared myclass, the compiler has no way of knowing the size that must be allocated for the "a" class.

A reference or pointer alleviates this b/c a pointer or reference has a defined size at the time of compilation and thus the compiler knows the memory requirements.

like image 196
RC. Avatar answered Sep 25 '22 07:09

RC.