Forward declarations and shared_ptr

Baz picture Baz · May 16, 2013 · Viewed 17.8k times · Source

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.

Answer

jcoder picture jcoder · May 16, 2013

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