Sorry for the bad question formulation, could not find a better way to shortly describe my problem:
I have a class A with a pure virtual method that returns an object of type B. Class B has a member variable wich is a pointer to an object of class A. Is there a way to achieve this?
Example:
class A {
public:
B mymethod() const = 0;
}
struct B {
std::shared_ptr<A> mypointer;
}
If I include the files in each other the compiler tells me that one is not declared in this scope. How can I avoid this?
std::shared_ptr was designed to replace raw pointers - so in order to provide compatible semantics, it also can be used without a full type definition.
Implementation notes
In a typical implementation,
std::shared_ptrholds only two pointers:
- the stored pointer (one returned by
get())- a pointer to control block
So, forward declaration is enough:
A.h:
#include "B.h"
class A
{
public:
B mymethod() const = 0; //returns by value, so full definition of B is required (*)
};
B.h:
class A; //Forward declare A
struct B
{
std::shared_ptr<A> mypointer;
};
(*) In fact, in your case such include may not be required, since it's only a declaration of function returning B. As long as you separate declarations (.h) and actual body (.cpp) or simply forward-declare functions prototypes, headers for particular types should be only included by source files, that use them.
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