What are real-world examples of C++ multiple inheritance? [closed] - c++

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 2 years ago.
Improve this question
Besides textbook examples -- in the real world -- does it ever make sense to use multiple inheritance (where more than one of the base classes are not pure interfaces) in C++?

It's very common when using Policy-based design, for example.

Easiest to point at iostream, which inherits from istream and ostream. cin and cout are istream and ostream respectively but fstream derives from iostream.

Microsoft's ATL (Active Template Library) uses multiple inheritance as mixin classes:
http://en.wikipedia.org/wiki/Active_Template_Library

IMO, it's open to argument. Prior to templates, there were a fair number of cases that justified it. Basically, you could use base classes about like you can use policy classes with templates. For example, consider a template like:
template <typename policy1, typename policy2>
class whatever {
policy1 p1;
policy2 p2;
public:
void dosomething() { if (p1.enquire()) p2.dosomething(); }
};
If you'd rather not use templates for some reason, you can get (some) fairly similar capabilities with multiple inheritance:
class whatever : policy1, policy2 {
void dosomething() { if (enquire()) dosomething(); }
};
In both cases, you're basically embedding an instance of the "policy" into your new object. Since we're using private inheritance, there's no concern with the LSP -- much like with policy-based templates, the intent isn't to create a large hierarchy that asserts anything about relationships between the members of the hierarchy -- rather, it's simply about creating the ability to create a large variety of unrelated classes on demand.

I have used multiple inheritance in the 'real world' - in a job where I was involved in coding a mapping application.
Unfortunately, I cannot remember the exact example which I find incredibly frustrating.
However, here is an interesting article about points to consider and alternative patterns or solutions to consider using:
http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.2
I like the use of vehicles for the examples - particularly adding in the amphibious vehicle.

Multiple inheritance definitely has its place and it can be very useful. As a general guideline a base class should be abstract whenever possible, which means you shouldnt be able to create an object out of it, but nothing stop you from inheriting from concrete class. It is definitely a merit too t hat you can take advantage of the inherited implementation from base class. Example on one of the answer on iostream is a good one. Another example is perhaps to say modelling a employee who is also an owner/director of a business and you will model it as
public class Director
{
................
double CalculateDividend();
bool ApproveBudget();
};
public class Employee
{
................
double CalculateSalary();
};
public class WorkingDirector: Employee, Director
{
..............
};
Now a WorkingDirector object can do what an Employee and a Director can do, which is a perfect in realworld. We wouldnt even need to overwrite any method implementation.
In many cases implementing design patterns are also made easier with multiple inheritance support.

If we have a class batsman which has data members like no of runs,no. of sixes, no of fours, batting average, run-rate etc. We have another class 'Bowler' which may have data members like no.of wickets taken, runs-per-over, average-wicket etc. For a player who is an all rounder, the class 'All-Rounder' will be derived from both the classes 'Batsman' and "Bowler'.
This can be cited as a real world example of multiple inheritance

Related

Interface vs Implementation in C++. What does this mean? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am learning the concepts of inheritance, especially about access-specifiers, here I am confused about the protected access specifier. The members under protected can be accessible by the base class member functions and derived class member functions. There is a chance of messing up implementation of base class if we declare protected as access specifier. Its always better to declare data members under private rather than protected as only the interface is exposed and not the implementation section. We are declaring only the variables in the private section of a class and how it becomes implementation? Implementation will be done in the member functions right? The terms are confusing, can anyone clarify and explain me the terms?
Interface and implementation are not ideas specific to C++ and it sounds like you're confused about what interfaces vs. implementations are in general, so hopefully by explaining what they are it will be easier to understand it in C++.
This SO question (though not exactly what you're asking) has a good definition for what an interface is:
An interface is a contract: the guy writing the interface says, "hey, I accept things looking that way", and the guy using the interface says "Ok, the class I write looks that way".
An interface is an empty shell, there are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.
And in his example the interface is (translated to C++):
class MotorVehicle
{
public:
virtual void run() const = 0;
virtual int getFuel() const = 0;
}
And then the implementation is:
class Car : public MotorVehicle
{
int fuel;
public:
void run() const override
{
printf("Wrroooooooom\n");
}
int getFuel() const override
{
return this->fuel;
}
}
The implementation is the actual substance behind the idea, the actual definition of how the interface will do what we expect it to. Another example: in terms of algorithms we talk about a Depth First Search (DFS) and it has a clearly defined behavior, but how we code, or implement, that algorithm can vary. We could use recursion or a stack data structure, for instance.
Now as regards access specifiers: it is not bad to use protected access. We talk about inheritance as an "is-a" relationship. When we say Cat inherits from Animal, we also say Cat is an Animal. So for the Cat to use some of the instance variables of the Animal is perfectly normal because it should belong to the Cat anyway.
You're worried that something the subclass does will mess up what the superclass does by changing the instance variables. You can certainly do that by throwing in meaningless data from the subclass, but usually you don't do that. You use the instance variables as the superclass intended them to be used (otherwise you would indeed screw up the functionality), which should be documented. If you are still thinking that someone should really not use your instance variables then that's what the private specifier is for.
One last thing: overriding superclass methods should also prevent misuse of superclass variables. By accessing and writing to protected variables you might change the behavior of superclass methods to something undesired, but then those methods should be overridden to do the new thing that your subclass is intending to do.

Difference between interface and polymorphism [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I was reading an online excerpt from a C++ book on polymorphism and interfaces.
The book made a distinction between polymorphism and interfaces, and specified how to implement them in C++. However, I was always under the idea that interfaces in C++ (implemented using a base class with pure virtual functions) were nothing more than an application of polymorphism.
I would like to know the clear distinction between polymorphism and interfaces because the excerpt confused me.
Polymorphism is the abstract concept of dealing with multiple types in a uniform manner, and interfaces are a way to implement that concept. Code that interacts with an interface can interact with any type that provides that interface.
Note that C++ has (at least) two forms of polymorphism: dynamic (i.e. run-time) polymorphism via interfaces formally defined by virtual functions, and static (i.e. compile-time) polymorphism via interfaces informally defined by the use of template parameters.
Typical C++ interfaces make use of virtual functions and polymorphism to provide the actual implementation. But polymorphism covers many other things, which is "not interfaces".
An interface is a base-class that can be used to a class that is passed back to something that accepts that interface. In some cases, a class may provide more than one interface:
class MyClass: public InterfaceGUI, InterfaceAudio
{
....
};
here, MyClass provides a class that interfaces both with the GUI and the Audio interfaces. This is a one case of multiple inheritance.
On the other hand:
class Animal
{
int numLegs;
public:
Animal(int nLegs): numLegs(nLegs) {}
};
class Dog : public Animal
{
Dog() : Animal(4) { }
};
here Animal is not a pure interface class, since it implements some functionality, and this is generally not a good design for an interface.
What i understood from the concept of polymorphism and Interface is as follows:
Polymorphism :
Polymorphism is nothing but having more than one form(As per all books).
But As per the Object orientation when you relate it with the real life You will get to know that Polymorphism is nothing but having more than one form with same name or some other Quality but have one's own Patent quality which no one have.
As per the programming:
A function with same name But different arguments (Compile time Polymorphism) and a Virtual function used for Runtime Polymorphism As explained here
Check this Example
Interface
An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data.
For this purpose we use Pure Virtual function
For Reference you can go through this Link
And for example you can use explanation by Mats Petersson
Hope this will help you to understand the basic senario.

Why is Multiple Inheritance in Classes avoided? [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 9 years ago.
Improve this question
Is it because it is very confusing and sometimes fields get intermixed or some other reason? Its allowed is C++ but not in Java??
For Example:
herbivore and carnivore are derived from animal and omnivore is derived from both herbivore and carnivore. So won't some fields get mixed up.
It is not avoided at all in C++. std::iostream uses multiple inheritance and is part of the standard classes. It's pretty hard to write a non trivial program without using it (think about std::fstream or std::stringstream).
http://www.cplusplus.com/reference/istream/basic_iostream/
http://www.cplusplus.com/reference/fstream/basic_fstream/
http://www.cplusplus.com/reference/sstream/basic_stringstream/
Why is Multiple Inheritance in Classes avoided? Is it because it is very confusing and sometimes fields get intermixed or some other reason?
Multiple inheritance is often avoided because it leads to several problems which can be difficult to fix for a novice programmer. Possible problems:
Diamond inheritance.
Carelessly Inheriting multiple interfaces (which weren't carefully designed) can pollute object's "public" or "protected" section with methods that aren't that useful for this particular object.
You have to be aware of construction/destruction order when object inherits several other objects, otherwise you might get crashes due to undefined behavior caused by things like double-delete. In other words, If object C inherits objects A and B, and ~A somehow uses something provided by object B, then ~A should be called before ~B. I.e. in this scenario class C: public B, public A{}: will work, but class C: public A, public B{}; will crash when destroyed. Bug like this can be hard to find.
but not in Java??
Ask java question for that.
Its allowed is C++
Multiple inheritance is available in C++ because it is useful.
Typical scenario - there are couple of abstract interfaces your class has to support. Let's say "IReader", "IWriter" and "IUglyObject". Which have no common ancestor.
To support several interfaces without multiple inheritance, you'll either have to make sure all your interfaces have common ancestor (which isn't always possible) or you'll have to define extra classes (derived from interfaces you want to support), write a lot of glue code that forward calls from your class to derived classes, which is too much typing. With multiple inheritance you can simply protected inherit all your interfaces and add few methods that return pointer to required interface.
class MyClass: protected ISomething, protected ISomethingElse{
public:
ISomething* getSomethingInterface(){ return this;}
ISomethingElse* getSomethingEkseInterface(){ return this;}
protected:
};
herbivore and carnivore are derived from animal and omnivore is derived from both herbivore and carnivore. So won't some fields get mixed up.
There are many ways to design hierarchy of classes, and the method you used in this example is not perfect. I could, for example, abstract "eating behavior" class and store it in "animal". That would allow me to change animal behavior on the fly and temporarily turn rabbits carnivores. Or I could create virtual method that either returns list of food types the animal accepts (or tests if the food is acceptable by this animal), that would allow me to make an animel that wants to eat only fried eggs and nothing else. There are other ways.
Class hierarchy doesn't have to mimic real world, you know...
when I was still learning C++, MI would often blow my mind and result in bad things when experimenting.
If you're new, then avoid it for now. Multiple Inheritance is useful in the scenario I listed - class supporting multiple different interfaces without writing glue code. In all other cases it can be avoided and probably isn't necessary.
If language has a feature, it doesn't mean you have to use this feature.
If language has a feature with bad reputation, doesn't mean you should never use it.
Choose your tools based on situation.

Private inheritance and composition, which one is best and why? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
suppose i have a class engin and i inherit a class car from engin class
class engin
{
public:
engin(int nobofcylinders);
void start();
};
class car:private engin
{
public:
car():e(8){}
void start()
{
e.start();
}
private:
engin e;
};
now the same can be done by the composition, the question is which approch would be best and is mostly used in programming, and why???????
Composition is to be preferred for two main reasons:
the thing(s) being composed can have names
you can compose more than one thing of the same type
I prefer to think of inheritance as derived is a kind of base, that basically means public inheritance. In case of private inheritance it more like derived has a base, which IMHO doesn't sound right, because that's IMHO the work for composition not inheritance of any kind. So, since private inheritance and composition essentially mean same thing logically, which to choose? With the example you posted, I'd most certainly go for composition. Why? I tend to think of all kinds of inheritance as a kind of relationship, and with the example you posted, I can't think of a situation where I could say a car is kind of an engine, it simply isn't. It's indeed like a car has an engine, so why would a car inherit from an engine? I see no reason.
Now, indeed there are cases where it's good to have private inheritance, namely boost::noncopyable, with it's ctor/dtor being protected, you'd have hard time instantiating it, and indeed since we want our class to have a noncopyable part, that's the only way to go.
Some style guides (e.g. google c++ style guide) even recommend to never use private inheritance, for reasons similar to what I already written - private inheritance is just a bit confusing.
If you want to compare private inheritance with composition, read http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.3. I don't think private inheritance is good.
A Car has-an Engine, but a Car is-not-an Engine, so it should be better done with composition.
Inheritence is useful for "is-a" relationships, e.g. a Bus is-a Car, a Car is-a vehicle, etc.
Composition is useful for "has-a" relationships, e.g. a Car has Wheel-s, a Car has-an Engine, etc.
So a logical code should be like
class Car : public Vehicle {
Engine engine;
Wheel wheels[4];
...
};
Private inheritance, despite the name, isn’t really inheritance – at least not from the outside (of the class), where it matters.
For that reason, different rules apply. In C++, private inheritance is said to model an “is implemented in terms of” relationship. Thus, a priority queue which is implemented in terms of a heap, could look like this:
template <typename T, typename Comp = std::less<T> >
class priority_queue : private heap<T, Comp> {
// …
};
Personally, I don’t see the advantage of this pattern, and Neil has already stated that in most cases, composition actually has the advantage over private inheritance.
One advantage exists, though: since it’s such an established pattern, the meaning of a private inheritance is immediately clear to a seasoned C++ programmer; the above code would tell them that the priority queue is implemented in terms of a heap – which wouldn’t be obvious if the class just happened to use a heap as one of its members.
Private inheritance tends to get used in C++ primarily for policy classes. The classical example is allocators, which determine how a container class manages storage internally:
template <typename T, typename A = std::allocator<T> >
class vector : private A {
// …
};
No harm done. But once again, this could also have been done using composition.
Usually, composition is to be preferred (others gave the major reasons), but private inheritance allows things which can't be done by composition:
zero-size base class optimization (a base class of size zero will not increase the size of a class, a member of size zero will), that't the reason behind its use for policy classes which often have no data members
controlling initialization order so that what is composed is initialized before a public base
overriding a virtual member in what is composed
with private virtual inheritance, ensuring that there is only one composed thing even if one do it in several bases
Note that for the later two uses, the fact that the base class exist can be observed in a descendant.
Composition is used more than private inheritance. The general rule I follow and would recommend is that unless you have a specific reason to use private inheritance you should use composition.
Composition has many benefits over private inheritance:
You can have more than one instance of a particular class.
You don't pollute your class' namespace with a bunch of private functions that don't make sense for your class.
You can give names to the parts of your object
Your class is less coupled to the classes it's composed of than it is to a class it inherits from
If you discover you need to swap out an object that you've included by composition during the lifetime of your object, you can, with private inheritance you're stuck.
There are a lot of other benefits to composition. Basically, it's more flexible and cleaner.
There are reasons to use private inheritance though. They are very specific reasons, and if you think they apply, you should think carefully about your design to make sure you have to do it that way.
You can override virtual functions.
You can get access to protected members of the base class.
You need to pass yourself to something that wants an object of the class you're inheriting from (this usually goes hand-in-hand with overriding virtual functions).
And there are a few rather tricky ones as well:
If you use composition for a class that has 0 size, it still takes up space, but with private inheritance it doesn't.
You want to call a particular constructor for a virtual base class of the class you're going to privately inherit from.
If you want to initialize the private base before other base classes are initialized (with composition, all the variables in your class will be initialized after all your base classes are).
Using private virtual inheritance to make sure there's only one copy of a thing even when you have multiple base classes that have it. (In my opinion, this is better solved using pointers and normal composition.)
Private inheritance means
is-implemented-in-terms of. It's
usually inferior to composition, but
it makes sense when a derived class
needs access to protected base class
members or needs to redefine
inherited virtual functions.
Unlike composition, private
inheritance can enable the empty base
optimization. This can be important
for library developers who strive to
minimize object sizes.
Scott Meyers "Effective C++" Third Edition.
Base classes are evil.
In my mind, good OO design is about encapsulation and interfaces. The convenience of base classes are not worth the price you pay.
Here's a really good article about this:
http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html

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/