Assume I have the following abstract class and use it as an "interface" in C++:
class IDemo
{
public:
virtual ~IDemo() {}
virtual void Start() = 0;
};
class MyDemo : IDemo
{
public:
virtual void start()
{
//do stuff
}
};
Then in the class that need to have a handle to the interface (concrete class through injection):
class Project
{
public:
Project(IDemo demo);
private:
IDemo *_demo;
};
My intention is to assign concrete Demo class through the constructor of Project. This code doesn't compile since IDemo can't be instantiated. Any suggestions? Thanks in advance.
It depends. If the concrete
Demo
object is not owned byProject
, use a reference:If you want ownership, use a
boost::shared_ptr
:In C++0x you can also use an
std::unique_ptr
, if you do not want shared ownership.Try:
But If the demo object is never going to change for the lifetime of the project then I prefer to pass by reference:
Then use it like this:
Must be:
Note
(1)
class MyDemo : public IDemo
(2)
IDemo* demo
already suggested earlier (or you may also useIDemo& demo
but it is conventional to use pointer to interface).(3)
virtual void Start() {...}
instead ofstart
(identifiers are case-sensitive).Should be
Without seeing the exact compiler warning I suggest you change
To