How NOT to use virtual inheritance? - c++

I am making a win32 api program. I first created a base class called WinClass and inherited like a dozen other classes from it. Now I need to create a derived class from two classes inherited from base class WinControl and WinHandler.Since I intend to make many more derived classes out of the original dozen, I'll have to use virtual inheritance on like every class inherited from WinClass.So is there any way to do this without using virtual inheritance?

Learn how to avoid overuse of inheritance at all. For example, read this article
http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/
A good start to learn how to get things done the way you want it (with the correct use of inheritance) is the book "Design Patterns":
http://c2.com/cgi/wiki?DesignPatternsBook

I first created a base class called WinClass and inherited like a dozen other classes from it.
And there's your first problem. If WPF has taught us anything, it should be that inheritance is not necessarily the best model for GUI design.
So is there any way to do this WITHOUT using virtual inheritance?
Yes: don't have WinControl and WinHandler be derived from WinClass. You haven't said what these do, so I can't offer any specific advice about them. Really, it seems like what you need is a "has a" relationship rather than the "is a" relationship that inheritance brings.
Also, there's no need to use boldface for class names. Just use the code tags that StackOverflow provides. Nor is there a need to SHOUT in bold-face.

Related

Example for non-virtual multiple inheritance

Is there a real-world example where non-virtual multiple inheritance is being used? I'd like to have one mostly for didactic reasons. Slapping around classes named A, B, C, and D, where B and C inherit from A and D inherits from B and C is perfectly fine for explaining the question "Does/Should a D object have one or two A sub-objects?", but bears no weight about why we even have both options. Many examples care about why we do want virtual inheritance, but why would we not want virtual inheritance?
I know what virtual base classes are and how to express that stuff in code. I know about diamond inheritance and examples of multiple inheritance with a virtual base class are abundant.
The best I could find is vehicles. The base class is Vehicle which is inherited by Car and Boat. Among other things, a Vehicle has occupants() and a max_speed(). So an Amphibian that inherits from both Car and Boat inherits different max_speed() on land and water – and that makes sense –, but also different occupants() – and that does not make sense. So the Vehicle sub-objects aren't really independent; that is another problem which might be interesting to solve, but this is not the question.
Is there an example, that makes sense as a real-world model, where the two sub-objects are really independent?
You're thinking like an OOP programmer, trying to design abstract models of things. C++ multiple inheritance, like many things in C++, is a tool that has a particular effect. Whether it maps onto some OOP model is irrelevant next to the utility of the tool itself. To put it another way, you don't need a "real-world model" to justify non-virtual inheritance; you just need a real-world use case.
Because a derived class inherits the members of a base class, inheritance often is used in C++ as a means of collecting a set of common functionality together, sometimes with minimal interaction from the derived class, and injecting this functionality directly into the derived class.
The Curiously Recurring Template Pattern and other mixin-like constructs are mechanisms for doing this. The idea is that you have a base class that is a template, and its template parameter is the derived class that uses it. This allows the base class to have some access to the derived class itself without virtual functions.
The simplest example I can think of in C++ is enable_shared_from_this, which allows an object whose lifetime is currently managed by a shared_ptr to actually retrieve a shared_ptr to that object just from a pointer/reference to that object. That uses CRTP to add the various members and interfaces needed to make shared_from_this possible to the derived class. And since the inheritance is public, it also allows shared_ptr's various functions that "enable shared_from_this" to to detect that a particular type has the shared_from_this stuff in it and to properly initialize it.
enable_shared_from_this doesn't need virtual inheritance, and indeed would probably not work very well with it.
Now imagine that I have some other CRTP class that injects some other functionality into an object. This functionality has nothing to do with shared_ptr, but it uses CRTP and inheritance.
Well, if I now write some type that wants to inherit from both enable_shared_from_this and this other functionality, well, that works just fine. There is no need for virtual inheritance, and in fact doing so would only make composition that much harder.
Virtual inheritance is not free. It fundamentally changes a bunch of things about how a type relates to its base classes. If you inherit from such a type, your constructors have to initialize any virtual base classes directly. The layout of such a type is very odd and is highly unlikely to be standardized. And various other things. C++ tries not to make programmers pay for functionality they don't use, so if you don't need the special properties of virtual inheritance, you shouldn't be using it.
Its the same reason C++ has non-virtual methods -- because the implementation is simpler and more efficient if you use non-virtual inheritance, so you need to explicitly ask for virtual inheritance if you want it. Since you don't need it if your classes never use multiple inheritance, that is the default.

When is virtual inheritance a good idea?

I'm making a game GUI API where each widget inherits from the Widget class. I was thinking, when others make there own widgets, they might not be fully satisfied with the base class. They might want to add getTheme() for example. Would it be a good idea to make all my widgets virtually inherit from Widget then so that this is possible?
Thanks
Just because the user would add their own methods to a child class doesn't mean you need to use virtual inheritance. You would use it if, in your library, you have a single base class with multiple children, and people could inherit from multiple child classes at once (for example mixin rather than substitution).
To resolve a diamond-shaped inheritance problem. (B and C both inherit from A. What happens to A's attributes in D that itself inherits from B and C?)
A client of your library could see a RedWidget and a FlyingWidget, and might want to combine them into a RedFlyingWidget.
User would have to specify one of the base classes to be virtual when inheriting. But that is not responsibility of a library maker.
OOP flows better with single-implementation inheritance, so that's what I'd use throughout a library.
There are also "upside-down inheritance" trees, as described by Alexandrescu's excellent "Modern C++ Design." They allow clients to pull in more functionality in a form of mix-ins that are called policies.
Programming with policies allows for greater ability to combine functionality, at the expense of syntactical cleanliness. Think STL implementation, for example.
When is virtual inheritance a good idea?
That's a design question.
For your Widgets, I would say Yes, multi-derived classes should have the option to be just 1 Widget.
Whenever there is a possibility that the users of your library are going to use several classes from your library as a base class (ie derive from them), you have to use virtual inheritance. In other words, it is a good idea to use it in your case.

Proper inheritance

What is meant by proper inheritance?
This thread gives a nice summary:
Proper inheritance occurs when the derived class "IS A" specialized type of the base class. Example Cat IS A Animal.
Improper inheritance occurs when a class is inherited from merely for code reuse without having any other relationship. Example Cat Inherits from Engine. A Cat is not an engine however both an engine and a cat purr.
I would like to add to what Justin and Baxter said.
The term proper inheritance is not really well-defined. Properly using inheritance is quite a subjective issue...
Consider the following example:
An interface: Bird
A concrete class: Ostrich
Should Ostrich inherits from Bird ? From a zoological point of view it makes sense, but from a Computer Science point of view... not so much. If Bird has a fly method, then how am I supposed to handle this in Ostrich::fly :x ?
There is somewhat of a war in the CS community. Indeed you'll regularly see books where Circle inherits from Ellipse (or the other way around) when it doesn't really makes sense from a CS point of view.
So my own little definition:
Considering that the interface defines precise semantics for each of its methods, a concrete class should only inherit from the interface if the implementation of each of the method matches the semantics specified.
Perhaps first we should recall what the value of inheritance itself is. Inheritance is a mechanism for both code reuse and interface reuse (polymorphism). But you can have code reuse without inheritance by using composition and delegation. And in many languages you can have polymorphism without inheritance, but not all languages. In a strongly typed language such as C++, polymorphism, which is itself another important code reuse mechanism, can only be achieved using inheritance. In fact, C++ distinguishes between public and private inheritance for interface and code reuse respectively. More on this later.
Generally one thinks of a class's methods as creating a contract with clients of the class: It guarantees that as long as you call a method having met certain preconditions, the method will deliver certain results. "Proper" inheritance is such that the subclass instance can be substituted for its parent class without violating the parent's contract. That is, none of the subclass's methods should override its base class's methods requiring stricter preconditions nor delivering more "less" results. Returning to C++, since there is a clear distinction between public and private inheritance where the former is required so that you may substitute a subclass instance for a base class instance, it is generally considered "proper" that the substitution be semantically correct. Otherwise why not use private inheritance?
Is Ostrich a valid subclass of Bird? It depends on what your abstraction of Bird is? If the Bird class has a method Bird::fly that does something tangible but Ostrich::fly overrides this to throw an exception and thus delivers "less" than its base class, I would say no. But if class Bird did not have a fly method (there is another subclass Flying_Bird that does), no problem.
My answer is that what holds for C++ is not a bad guideline for any object-oriented language. In a languages like Python where an inheritance hierarchy is not required for polymorphism, people might have a greater tendency to use inheritance just for code reuse. If this reuse is well-documented, it might not be an issue. But when I see a class hierarchy, my expectation is that a subclass is potentially going to be used polymorphically and thus an instance of the subclass can be substituted for an instance of the base class thereby obeyeing the Liskov substitution principle where a subclass is also a subtype.
When inheritance complies with a IS A relationship, as opposed to inheriting purely for code reuse without there being a logical subsumption of the child by the superclass.

Using non-abstract class as base

I need to finish others developer work but problem is that he started in different way...
So now I found in situation to use existing code where he chooses to inherit a non-abstract class (very big class, without any virtual functions) that already implements bunch of interfaces or to dismiss that code (which shouldn't be to much work) and to write another class that implements interfaces I need.
What are the pros and cons that would help me to choose the better approach.
p.s. please note that I don't have to much experience
Many Thanks
Although it is very tempting to say write it from scratch again, don't do it! The existing code may be ugly, but it looks like it does work. Since the class is big, I assume there is fair bit of history behind it as well. It might have solutions for some very obscure cases which you might not have imagined till now. What I suggest is, if possible first talk to the person who developed that class, understand how it works, then derive from it (after making its destructor virtual of course) and complete your work. Then as and when time permits slowly refactor the parts of the class into smaller more manageable classes. Also, don't forget to write a good unit-tester before you start so that you can validate the new behavior against the existing class's behavior. One more thing, there is nothing wrong in inheriting from a non-abstract base class as long as it makes sense and the base class destructor is virtual.
If the other developer has written a base-class with no virtual functions, then those functions do not need to be overridden, and it is correct to define them in a non-abstract base class.
If those functions define functionality that all the child-classes require then it would be a mistake to get rid of the base class, as you would then need to implement those functions individually in each of the child classes.
I've seen a lot of developers go 'interface-mad' in the last couple of years, but base classes still serve a function over interfaces - to provide a concrete implementation that is common to all child classes. It would be a mistake to get rid of the base class and have seperate implementations of these functions in each of the child classes.
HOWEVER, if the child classes are inheriting functionality that they do not require, or require a separate implementation of, then the Base class is a mistake and interfaces would seem like the better option to divide the functionality between the child classes.
Despite this, I would agree with Naveen that its probably not worth the extra work this will give you, it may seem simple, but if this is a big class with a lot of inheritors then it could turn out to be a nightmare. Quite often in Software Engineering you have to deal with another developer's code that you might have implemented differently. If you re-implemented it ever time you will be a very unproductive developer. I say work with what you've got and get the project finished on time.
Is there anything at all you want to use from the base class or would you end up overriding everything?
Does it define some sort of type that you want to use for an "is-a" relationship?
(for example, base class is "animal" and you want to make "cat", but if it doesn't add any behavior to its interface, that doesn't seem likely)
Is the base class used in other interfaces you need to use? (like if someone is passing objects through a reference/pointer to the base class)
If not, I'd say there's no advantage in inheriting from that class over implementing the interface(s) yourself.
What are the pros and cons that would help me to choose the better approach.
It's legal to derive from a class with no virtual functions, but that doesn't make it a good idea. When you derive from a class with virtual functions, you often use that class through pointers (eg., a class Derived that inherits from Base is often manipulated through Base*s). That doesn't work when you don't use virtual functions. Also, if you have a pointer to the base class, delete-ing it can lead to a memory leak.
However, it sounds more like these classes aren't being used through pointers-to-the-base. Instead the base class is simply used to get a lot of built in functionality, although the classes aren't related in the normal sense. Inversion of control (and has-a relationships) is a more common way to do that nowadays (split the functionality of the base class into a number of interfaces -- pure virtual base classes -- and then have the objects that currently derive from the base class instead have member variables of those interfaces).
At the very least, you'll want to split the big base class into well-defined smaller classes and use those (like mixins), which sounds like your second option.
However, that doesn't mean rewrite all the other code that uses the blob base class all in one go. That's a big undertaking and you're likely to make small typos and similar mistakes. Instead, buy yourself copies of Working Effectively With Legacy Code and Large-Scale C++ Software Design, and do the work piecemeal.
From you question it is not too clear what the problem is - looking at the title (Using non-abstract class as base) I can tell you that using an abstract class (non pure virtual - when you talk about interfaces in C++ I am assuming pure virtual abstract classes) as base makes sense only if there is common functionality you can share between subclasses - meaning that a number of classes extend the same abstract class inheriting the common implementation. If that's not the case (and you're pretty confident it's never gonna happen) then it doesn't make sense to use an abstract class.
If you can extract out some of the functionality in you big class in such a way that leads to (even potential) code reuse then it could make sense - otherwise I wouldn't see the point.

When might multiple inheritance be the only reasonable solution? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
To be clear, I'm not asking if/why multiple inheritance is good or bad. I've heard a lot of arguments from both sides of that debate.
I'm wondering if there is any kind of design problem or scenario in C++ in which multiple inheritance is either the only way to accomplish something, or at least is the most optimal way over all other alternatives to the point that it wouldn't make sense to consider anything else.
Obviously, this question doesn't apply to languages that don't support multiple inheritance.
You can't do policy-based design without multiple inheritance. So if policy-based design is the most elegant way to solve your problem, than that means you need multiple inheritance to solve your problem, over all other options.
Multiple-inheritance can be very useful if it's not misused (like everything, in any language).
There is a situation in which you would inherit from a class and maybe implement one or two interfaces in Java. This is something you would resolve with multiple inheritance in c++ I think.
C++ streams use multiple inheritance: istream and ostream are both parents of iostream. Since they both inherit from ios_base, you have a diamond.
It's the only "reasonable" solution in the sense that it would be unreasonable for the streams part of the standard libraries to take the same line as the algorithms and collections. So ostream behaves polymorphically rather than being a "duck-typed" interface like Iterator(*).
As soon as you have dynamic polymorphism, you need multiple inheritance to implement more than one interface at the same time.
(*) Presumably this is because anything else would be a shambles. You have to be able to write actual functions which manipulate streams, rather than forcing users to have templates everywhere. This is because it's common to write to "some stream, I don't know what until runtime", but not to want to manipulate "some collection, I don't know what until runtime".
Multiple inheritance is useful if you need to inherit behavior, not just contract. However, as other languages demonstrate, multiple inheritance is not the only way to solve that problem, at the expense of making your inheritance tree deeper. As such, scenarios where you must and may only use multiple inheritance would be pretty rare.
I'd read up on Java Interfaces, and so on, to get a better idea as to the answer to this question. The idea behind an Interface is to create an abstract class that acts as a template for another class. the advantage, here, is that the templates can be combined within a concrete class. For example-
Parent class- FoodStore
Subclass- CoffeeShop
Subclass- Bakery
With this inheritance tree, a FoodStore can be a Bakery or a CoffeeShop but not both. But then what would we call a Starbucks?
Better way, IMO-
Parent Class- FoodStore
Interface- CoffeeShop
Interface- Bakery
public class Starbucks extends FoodStore implements CoffeeShop, Bakery { ... }
You'll have to know a bit of Java to understand that, but have at it. Interfaces are fairly elementary, IMO.
As a further musing, perhaps Interfaces are designed to obey "Don't repeat yourself." Obvious, now that I mention it.
When you want to inherit functionality rather than role, case in point boost::noncopyable (other languages that support this (unlike Java and C#) call this a mixin).
As have been said on the other answers:
Using pure virtual base classes as "Interfaces", as in Java ( http://en.wikipedia.org/wiki/Interface_(Java) ), this is a very common O.O. pattern in all O.O. languages, not only Java
To do police-based design
But also:
To compose a class with several mixins ( http://en.wikipedia.org/wiki/Mixin ); I consider this a very good use of multiple inheritance to achieve code reuse!
When you must combine two or more third-party class hierarchies, each of which requires that objects be derived from the hierarchy's own Base class, then lacking multiple inheritance will make your code complex and fiddly.
namespace Object_Database {
class Object {
public:
virtual void store() ;
virtual void fetch() ;
};
}
namespace Reflectives {
class Object {
public:
virtual std::vector<std::string> > membernames();
virtual std::vector<std::string> > methodnames();
};
}
The first hierarchy lets users create objects which can be serialized to and from an object database, and requires that all such objects be derived from class Object_Database::Object. The second hierarchy lets users create objects which can be queried at runtime for the names of their members, and requires that all such objects be derived from Reflectives::Object.
If you require objects that can do both, you just need to write:
class ReflectivePickle :
public Object_Database::Object,
public Reflectives::Object {
// ...
};
The other solutions are unreasonable.
I tend to use multiple inheritance in C++ when the base classes are "interface classes", i.e. base classes where all methods are pure virtual, none have implementations [remember you can still define an implementation, but you have to invoke it explicitly], and there are no data members. Very similar to "interfaces" in Java or (from what I hear) C#.
To use polymorphism in C++, you can't use composition, you have to use (public) inheritance.
So if class Bar inherits (publicly) from Printable and Serializable, I can treat the object like a printable object, a serializable object, or a Bar object (using pointers or references).
With composition, you can't do that.
If you want to see a beautiful implementation of Multiple Inheritance check out Eiffel. They solve the diamond problem through feature renaming, far simpler than scope resolution and it even supports direct repeated inheritance such that:
A inherit B, B, B
when the need arises to use this type of inheritance.
Their Kernel library is open source and multiple inheritance is used extensively if you would like to see examples.
http://sourceforge.net/projects/eiffelstudio/files/