C++ interfaces - what are my options? - c++

Diving back into the world of C++, and experimenting with interfaces. I can find plenty of online examples, but 99% of them are trivial 'all-in-one-file'.
Interfaces can be classified into 3 basic types- interfaces where (all|some|zero) functions must be overridden in a concrete subclass (all|some|zero pure virtual functions in c++ parlance).
Is it possible to implement any of the 3 in a single header file? (no .cpp twin) Why/why not? How? If not, what are my options for the .h/.cpp pair?
Some of the options I have seen are: virtual destructor, protected destructor, inline destructor, pure virtual destructor with an implementation,... my head is spinning!
EDIT: meant pure virtual, not virtual void

If you make your interface pure virtual, the compiler will give an error if you forget to implement a method in your concrete class.
If there are methods that have some sane default implementation you can provide it, but this is just a convenience.
If you make the destructor virtual, you can delete the object via its interface pointer rather than requiring the concrete object pointer.
Herb Sutter has some interesting thoughts on interfaces which are at direct odds with the way most of us implement an interface: http://www.gotw.ca/publications/mill18.htm

Read this awesome piece of internet wisdom: http://www.parashift.com/c++-faq-lite/dtors.html
1) You never need a .cpp file, you can code all your programs in .h, but doing this is terrible style and will inevitabely slow your compilation.
MyClass : public MyInterface {
public:
virtual void myFunction() {
// override and implemenht
}
};
2) When inheriting classes you don't need to worry about declaring your destructor to be virtual, but you need to make sure that classes you are inheriting from have virtual destructors. Otherwise you might be faced with memory leaks. In so far as I know this is not necessary for interface classes with only pure virtual functions.
Destructor being inline makes no difference to you.
Destructor being declared as void is something that should give you a compiler error :).
Edit:
About the 3 types of interfaces, I am getting the sense that you are a little bit confused and this is hampering your googling.
An interface is usually a class that has no functions defined and you must inherit and implement all of them.
A class that has some functionality but still has some pure virtuals is usually called abstract.
When 'zero' functions must be overridden this is neither an interface nor an abstract class, it is just a plain old class that you can inherit and do whatever.
Check out the C++ faq.

Interface where all functions must be overridden by a concrete subclass is called interface
Interface where some functions must be overridden by a concrete subclass is called abstract class
Interface where zero functions must be overridden by a concrete subclass is called class.
You can implement virtual member functions inside header file. They will not inline though, because they have to have address to be placed into virtual table.
... my head is spinning!
To get it spinning more you can also have pure virtual destructor. This is useful trick when you want to have abstract class, but no real useful method to put pure virtual:
class A
{
public:
virtual ~A() = 0;
};
A::~A() {}
class B : public A
{
public:
~B() {}
};
Class A has destructor implemented, but it still can not be instantiated directly, because it is interface. Yet, when it comes to destroying B compiler has to obey to protocol and call ~A(). That is why you have to implement it

Related

Adding a body to a pure virtual/abstract function in C++?

A pure virtual function isn't supposed to have a body, but I just noticed that the following code is accepted by the compiler:
class foo
{
virtual void dummy() = 0
{
cout << "hello";
}
};
So, why are pure virtual functions allowed to have a body? Also, even when the function has a body, the class still can't be instantiated, why is that?
Pure virtual function can have a body, but the fact that you declare them pure virtual is exactly to say that a derived implementation is required.
You can execute the pure virtual method from a derived method (using an explicit BaseClass::method()) but still you have to provide an implementation.
Not being able to instantiate a class with a pure virtual method that has not been overriden is the main point of the pure virtual declaration. In other words the idea of declaring a method pure virtual is to ensure that the programmer will not forget about providing its implementation.
Generally speaking, abstract class is used to define interface and/or partial implementation, and is intended to be inherited by concrete classes. It is a way of enforcing a contract between class designer and users of that class, whatever they are.
If you don't need this contract and want instantiation, then do not enforce it to be abstract class, i.e. remove = 0.
If your concern is why would pure virtual functions have body in the first place, then one good example could be this quote from the Effective C++ book by Scott Meyers:
Derived classes that implement this pure virtual function may call
this implementation somewhere in their code. If part of the code of
two different derived classes is similar then it makes sense to move
it up in the hierarchy, even if the function should be pure virtual.
Another example is pure virtual destructor (which is also a function by the way):
...
virtual ~foo() = 0;
...
foo::~foo() {} // required!
when you are required to provide implementation for it, but at the same time want to make it pure virtual in order to make the foo class abstract. So, in fact, the core of the language itself relies on this feature.

How to define an interface in C++?

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 virtual destructor; otherwise you'll get into undefined behaviour if you try to invoke delete on 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.
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
Your instincts are correct on this one. Types with at least one pure virtual function can't be instantiated and will generate a compiler error.
You are doing correct:An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You cannot instantiate a virtual class.
You are correct in thinking that any class with a pure virtual method is abstract and cannot be instantiated.
Personally I tend to add a protected destructor to most of my interfaces as in many/most cases I don't want the code that uses the interface to be able to destroy it. Alternatively you should add a public virtual destructor (not pure, with an empty body!) so that the object can be deleted via the interface pointer and the correct destructors will be called.

Should methods that implement pure virtual methods of an interface class be declared virtual as well?

I read different opinions about this question. Let's say I have an interface class with a bunch of pure virtual methods. I implement those methods in a class that implements the interface and I do not expect to derive from the implementation.
Is there a need for declaring the methods in the implementation as virtual as well? If yes, why?
No - every function method declared virtual in the base class will be virtual in all derived classes.
But good coding practices are telling to declare those methods virtual.
virtual is optional in the derived class override declaration, but for clarity I personally include it.
Real need - no. Once a method is declared as virtual in the base class, it stays virtual for all derived classes. But it's good to know which method is virtual and which - not, instead of checking this in the base class. Also, in most cases, you cannot be sure, if your code will be derived or not (for example, if you're developing some software for some firm). As I said, it's not a problem, as once declared as virtual, it stays virtual, but just in case .. (:
There is no requirement to mark them virtual.
I'd start by arguing that virtual advertises to readers that you expect derived classes to override the virtual to do something useful. If you are implementing the virtual to do something, then the virtual method might have nothing to do with the kind of thing your class is: in which case marking it virtual is silly. consider:
class CommsObject {
virtual OnConnect();
virtual OnRawBytesIn();
};
class XMLStream : public CommsObject {
virtual OnConnect();
OnRawBytesIn();
virtual OnXMLData();
};
In that example, OnConnect is documented as virtual in both classes because it makes sense that a descendent would always want to know. OnRawBytesIn doesn't make sense to "Export" from XMLStream as it uses that to handle raw bytes, and generate parsed data - which it notifies via OnXMLData().
Having done all that, I'd then argue that the maintainer of a 3rd class, looking at XMLStream, might think that it would be "safe" to create their own OnRawBytes function and expect it to work as a normal overloaded function - i.e. the base class would call the internal correct one, and the outer one would mask the internal OnRawBytes.
So omitting the virtual has hidden important detail from consumers of the class and made the code behave in unexpected ways.
So ive gone full circle: Don't try to use it as a hint about the intended purpose of a function - DO use it as a hint about the behaviour of the function: mark functions virtual consistently so downstream programmers have to read less files to know how a function is going to behave when overridden.
No, it is not needed and it doesn't prevent any coding errors although many coders prefer to put it.
Once C++0x becomes mainstream you'll be able to use the override specifier instead.
Once 'virtual', it's virtual all the way down to the last child. Afaik, that's the feature of the c++.
If you never derive from a class then there is no point making its methods virtual.

Use-cases of pure virtual functions with body?

I recently came to know that in C++ pure virtual functions can optionally have a body.
What are the real-world use cases for such functions?
The classic is a pure virtual destructor:
class abstract {
public:
virtual ~abstract() = 0;
};
abstract::~abstract() {}
You make it pure because there's nothing else to make so, and you want the class to be abstract, but you have to provide an implementation nevertheless, because the derived classes' destructors call yours explicitly. Yeah, I know, a pretty silly textbook example, but as such it's a classic. It must have been in the first edition of The C++ Programming Language.
Anyway, I can't remember ever really needing the ability to implement a pure virtual function. To me it seems the only reason this feature is there is because it would have had to be explicitly disallowed and Stroustrup didn't see a reason for that.
If you ever feel you need this feature, you're probably on the wrong track with your design.
Pure virtual functions with or without a body simply mean that the derived types must provide their own implementation.
Pure virtual function bodies in the base class are useful if your derived classes wants to call your base class implementation.
One reason that an abstract base class (with a pure virtual function) might provide an implementation for a pure virtual function it declares is to let derived classes have an easy 'default' they can choose to use. There isn't a whole lot of advantage to this over a normal virtual function that can be optionally overridden - in fact, the only real difference is that you're forcing the derived class to be explicit about using the 'default' base class implementation:
class foo {
public:
virtual int interface();
};
int foo::interface()
{
printf( "default foo::interface() called\n");
return 0;
};
class pure_foo {
public:
virtual int interface() = 0;
};
int pure_foo::interface()
{
printf( "default pure_foo::interface() called\n");
return 42;
}
//------------------------------------
class foobar : public foo {
// no need to override to get default behavior
};
class foobar2 : public pure_foo {
public:
// need to be explicit about the override, even to get default behavior
virtual int interface();
};
int foobar2::interface()
{
// foobar is lazy; it'll just use pure_foo's default
return pure_foo::interface();
}
I'm not sure there's a whole lot of benefit - maybe in cases where a design started out with an abstract class, then over time found that a lot of the derived concrete classes were implementing the same behavior, so they decided to move that behavior into a base class implementation for the pure virtual function.
I suppose it might also be reasonable to put common behavior into the pure virtual function's base class implementation that the derived classes might be expected to modify/enhance/augment.
One use case is calling the pure virtual function from the constructor or the destructor of the class.
The almighty Herb Sutter, former chair of the C++ standard committee, did give 3 scenarios where you might consider providing implementations for pure virtual methods.
Gotta say that personally – I find none of them convincing, and generally consider this to be one of C++'s semantic warts. It seems C++ goes out of its way to build and tear apart abstract-parent vtables, then briefly exposes them only during child construction/destruction, and then the community experts unanimously recommend never to use them.
The only difference of virtual function with body and pure virtual function with body is that existence of second prevent instantiation. You can't mark class abstract in c++.
This question can really be confusing when learning OOD and C++. Personally, one thing constantly coming in my head was something like:
If I needed a Pure Virtual function to also have an implementation, so why make it "Pure" in first place ? Why not just leaving it only "Virtual" and have derivatives, both benefit and override the base implementation ?
The confusion comes to the fact that many developers consider the no body/implementation as the primary goal/benefit of defining a pure virtual function. This is not true!
The absence of body is in most cases a logical consequence of having a pure virtual function. The main benefit of having a pure virtual function is defining a contract: By defining a pure virtual function, you want to force every derivative to always provide their own implementation of the function. This "contract aspect" is very important especially if you are developing something like a public API. Making the function only virtual is not so sufficient because derivatives are no longer forced to provide their own implementation, therefore you may loose the contract aspect (which can be limiting in the case of a public API).
As commonly said :
"Virtual functions can be overrided, Pure Virtual functions must be overrided."
And in most cases, contracts are abstract concepts so it doesn't make sense for the corresponding pure virtual functions to have any implementation.
But sometimes, and because life is weird, you may want to establish a strong contract among derivatives and also want them to somehow benefit from some default implementation while specifying their own behavior for the contract. Even if most book authors recommend to avoid getting yourself into these situations, the language needed to provide a safety net to prevent the worst! A simple virtual function wouldn't be enough since there might be risk of escaping the contract. So the solution C++ provided was to allow pure virtual functions to also be able to provide a default implementation.
The Sutter article cited above gives interesting use cases of having Pure Virtual functions with body.

Are virtual destructors inherited?

If I have a base class with a virtual destructor. Has a derived class to declare a virtual destructor too?
class base {
public:
virtual ~base () {}
};
class derived : base {
public:
virtual ~derived () {} // 1)
~derived () {} // 2)
};
Concrete questions:
Is 1) and 2) the same? Is 2) automatically virtual because of its base or does it "stop" the virtualness?
Can the derived destructor be omitted if it has nothing to do?
What's the best practice for declaring the derived destructor? Declare it virtual, non-virtual or omit it if possible?
Yes, they are the same. The derived class not declaring something virtual does not stop it from being virtual. There is, in fact, no way to stop any method (destructor included) from being virtual in a derived class if it was virtual in a base class. In >=C++11 you can use final to prevent it from being overridden in derived classes, but that doesn't prevent it from being virtual.
Yes, a destructor in a derived class can be omitted if it has nothing to do. And it doesn't matter whether or not its virtual.
I would omit it if possible. And I always use either the virtual keyword or override for virtual functions in derived classes for reasons of clarity. People shouldn't have to go all the way up the inheritance hierarchy to figure out that a function is virtual. Additionally, if your class is copyable or movable without having to declare your own copy or move constructors, declaring a destructor of any kind (even if you define it as default) will force you to declare the copy and move constructors and assignment operators if you want them as the compiler will no longer put them in for you.
As a small point for item 3. It has been pointed out in comments that if a destructor is undeclared the compiler generates a default one (that is still virtual). And that default one is an inline function.
Inline functions potentially expose more of your program to changes in other parts of your program and make binary compatibility for shared libraries tricky. Also, the increased coupling can result in a lot of recompilation in the face of certain kinds of changes. For example, if you decide you really do want an implementation for your virtual destructor then every piece of code that called it will need to be recompiled. Whereas if you had declared it in the class body and then defined it empty in a .cpp file you would be fine changing it without recompiling.
My personal choice would still be to omit it when possible. In my opinion it clutters up the code, and the compiler can sometimes do slightly more efficient things with a default implementation over an empty one. But there are constraints you may be under that make that a poor choice.
The destructor is automatically virtual, as with all methods. You can't stop a method from being virtual in C++ (if it has already been declared virtual, that is, i.e. there's no equivalent of 'final' in Java)
Yes it can be omitted.
I would declare a virtual destructor if I intend for this class to be subclassed, no matter if it's subclassing another class or not, I also prefer to keep declaring methods virtual, even though it's not needed. This will keep subclasses working, should you ever decide to remove the inheritance. But I suppose this is just a matter of style.
A virtual member function will make implicitely any overloading of this function virtual.
So the virtual in 1) is "optional", the base class destructor being virtual makes all child destructors virtual too.
1/ Yes
2/ Yes, it will be generated by the compiler
3/ The choice between declaring it virtual or not should follow your convention for overriden virtual members -- IMHO, there are good arguments both way, just choose one and follow it.
I'd omit it if possible, but there is one thing which may incite you to declare it: if you use the compiler generated one, it is implicitly inline. There are time when you want to avoid inline members (dynamic libraries for instance).
Virtual functions are overridden implicitly. When the method of a child class matches the method signature of the virtual function from a base class, it is overridden.
This is easy to confuse and possibly break during refactoring, so there are override and final keywords since C++11 to mark this behavior explicitly. There is a corresponding warnings that forbid the silent behavior, for example -Wsuggest-override in GCC.
There is a related question for override and final keywords on SO: Is the 'override' keyword just a check for a overridden virtual method?.
And the documentation in the cpp reference https://en.cppreference.com/w/cpp/language/override
Whether to use override keyword with the destructors is still a bit of debate. For example see discussion in this related SO question: default override of virtual destructor
The issue is, that the semantics of the virtual destructor is different to normal functions. Destructors are chained, so all base classes destructors are called after child one. However, in case of a regular method base implementations of the overridden method are not called by default. They can be called manually when needed.