Byomeer
Byomeer

Reputation: 426

c++ return type has pointer with type of current class

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?

Upvotes: 3

Views: 312

Answers (1)

Mateusz Grzejek
Mateusz Grzejek

Reputation: 12068

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_ptr holds 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.

Upvotes: 5

Related Questions