Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top