Please consider a pure virtual class like this:
class Foo {
public: virtual int FooBar() = 0;
};
A Java developer would call such a thing an “Interface”. Usually, you then program to that interface, e.g. (bad example, sorry):
class Bar {
public: Foo f;
};
class Child : public Foo {
public: int FooBar() { return 1; }
};
Bar b;
b.foo = Child();
This does obviously not work in C++, because an instance of class Foo is created at construction time (but that’s not possible, because Foo is an abstract class).
Is there any pattern for “programming to an interface” in C++?
Edit: Clarified the example, sorry.
If you need something, that points to or references an implementation of an interface (or abstract class), you can use a pointer of a reference to that interface:
If you want to use a reference
Foo& f, a pointerFoo* for a reference or pointer to a const implementation (const Foo& fofconst Foo* f) or even a const pointer to const implementation (const Foo* const f) depends on your requirements.Use a reference if possible, for composition where the referenced implementation is passed from the outside (like in my example). Use a pointer or smart-pointer if the object is more of an aggregation and is constructed by the containing object itself.
Update:
As no one else mentioned it up to now, if you are going to allocate the object that implements the interface dynamically, the base class have to have a virtual destructor, or otherwise you will invoke undefined behavior, even if you use a smart pointer. And beware that smart pointer can be handy, but they are not a cure for all. You should still keep some owner hierarchy in mind or you will end up with cycles that can’t be resolved by smart pointers easily.