// 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)
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.
Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.
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 ...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With