13

I'm trying to refactor my code so that I use forward declarations instead of including lots of headers. I'm new to this and have a question regarding boost::shared_ptr.

Say I have the following interface:

#ifndef I_STARTER_H_
#define I_STARTER_H_

#include <boost/shared_ptr.hpp>

class IStarter
{
public:
    virtual ~IStarter() {};

    virtual operator()() = 0;
};

typedef boost::shared_ptr<IStarter> IStarterPtr;

#endif

I then have a function in another class which takes an IStarterPtr object as argument, say:

virtual void addStarter(IStarterPtr starter)
{
    _starter = starter;
}
...
IStarterPtr _starter;

how do I forward declare IStarterPtr without including IStarter.h?

I'm using C++98 if that is of relevance.

JBL
  • 12,588
  • 4
  • 53
  • 84
Baz
  • 12,713
  • 38
  • 145
  • 268

4 Answers4

12

Shared pointers work with forward declared types as long as you dont call * or -> on them so it should work to simply write :-

class IStarter;
typedef boost::shared_ptr<IStarter> IStarterPtr;

You need to include <boost/shared_ptr.hpp> of course

jcoder
  • 29,554
  • 19
  • 87
  • 130
2

Though it would add a header file, you could put that in a separate header file :

#include <boost/shared_ptr.hpp>

class IStarter;
typedef boost::shared_ptr<IStarter> IStarterPtr;

and then include it both in IStarter.h and in your other header, avoiding code duplication (though it's quite small in this case).

There might be better solutions though.

JBL
  • 12,588
  • 4
  • 53
  • 84
2

You can't forward declare typedefs in C++98 so what I usually do in this case is pull out the typedefs I need an put them into a types.h file, or something similar. That way the common type code is still separated from the definition of the class itself.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1

There is a way but you need to include the boost header in your file :

#include <boost/shared_ptr.hpp>

class IStarter;
typedef boost::shared_ptr<IStarter> IStarterPtr;

// ...

virtual void addStarter(IStarterPtr starter)
{
      _starter = starter;
}
// ...
IStarterPtr _starter;
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62