I’m working on a C++ class which provides an abstraction of BSD sockets for networking. I want to define an interface ISocket which is implemented by CSocket and MockSocket (the latter for unit testing). I know that I need to define the methods that I want implementing classes to provide as pure virtual, i.e.
class ISocket {
public:
virtual int Socket(int domain, int type, int protocol) = 0;
};
What I’m worried about is whether a class of type ISocket can be instantiated. My instincts tell me that any class with at least one pure virtual method is an abstract class (i.e. interface) and cannot be instantiated, but I have a niggling worry in the back of my mind that I need to do something about the auto-generated constructors and destructor that the C++ compiler will provide (Effective C++ is both a gift–when you remember everything you read in it–and a curse–when you don’t).
Am I doing this correctly, or is there a best practise for defining interfaces in C++ that I’m not following here?
In general, you should declare a
virtualdestructor; otherwise you’ll get into undefined behaviour if you try to invokedeleteon a pointer-to-interface. There are no such issues with constructors.Oh, and you are correct that it is not possible to instantiate an object of a class with a pure-virtual.