Difference between interface and polymorphism [closed] - c++

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.

Related

Is it an abstract class or a pure virtual (interface)?

It might be a silly question but I never saw a question about it or read about it.
Imagine that we have this:
class Numeric
{
public:
virtual ~Numeric() {}
virtual int getNumeric() const = 0;
};
This is considered an interface.
And now I insert an enumerator (It can be something else, like a typedef, etc.)
class Numeric
{
public:
enum Numbers
{
One,
Two,
};
virtual Numbers getNumeric() const = 0;
};
Still being an interface or it is now considered an abstract class?
As I said, it might be silly but I really wonder to know that.
If you are looking for an official answer, then I'm afraid there is none.
The draft of the C++11 standard I am having here merely says [10.4 class.abstract]:
An abstract class can also be used to define an interface for which
derived classes provide a variety of implementations.
All other instances of the word "interface" in the entire ~1300 pages PDF only refer to generic programming or other things not related to OOP or abstract classes.
For example this one here [24.2.1 iterator.requirements.general]:
Most of the library’s algorithmic templates that operate on data
structures have interfaces that use ranges.
This obviously has nothing to do with abstract classes.
Bjarne Stroustrup himself, if you accept his words as "half-official", doesn't really help you in this regard, either. Quoting from the glossary on his homepage:
abstract class - a class defining an interface only; used as a base
class.
You will have to live with the fact that the C++ language itself as well as C++ developers and experts use the word "interface" as a superset for "abstract class". Unlike e.g. in Java, where interfaces are an actual language element with its own interface keyword, there is no such thing in C++.
Everything else is opinion-based.
Your second class Numeric is an interface.
If a class has one or more pure virtual functions, then this class is called an "abstract class".
Generally, if all of a classes' functions are pure virtual functions, then this class is called an "interface".
C++ does not have an explicit interface concept, so the above two classes are called the interface or abstract class, somewhat interchangably.
In my opinion, your second class can be considered an interface. I don't think there is a standard which defines interfaces in C++. However in languages which have interfaces, for example, Java, you can usually have enums defined inside an interface.
I would consider a class with no implementation to be an interface.

Multiple inheritance with interface in C++ [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 8 years ago.
Improve this question
Is multiple inheritance with interface class a good design practice?
It seems to work and makes running gtest unittest suite convenient. So in example below, is multiple inheritance of class B a bad design practice?
#include <stdio.h>
class BInterface {
public:
virtual ~BInterface() {}
virtual void idb() = 0;
};
class A {
public:
A() {}
void ida() {printf("I am A\n");}
};
class B : public A, public BInterface { // ########### Is this OK? ############
public:
B() {}
void idb() {printf("I am B\n");}
};
int main() {
B BObject;
BInterface* BI = &BObject;
BI->idb();
return 0;
}
Edit: I am OK with just inheritance of interface class but is multiple inheritance in such case a bad design, considering that most of code experts recommend not to use multiple inheritance.
It's technically OK to inherit interface classes. After all that's what they're designed for. Whether it makes design level sense is another matter, not possible to decide without considering the particular design.
Within C++ there are some advantages of making interface inheritance virtual, in particular that you can inherit in an implementation, but it also can have a slight cost in efficiency.
Microsoft's COM is an example of an interface-based architecture that does not use virtual inheritance of interface. Use of virtual would have complicated1 the C view of a COM class. But for purely all-within-C++ code there is (hopefully) no such consideration.
Regarding
” in example below, is multiple inheritance of class B a bad design practice?
… there is no multiple inheritance of class B in the example as it is as of me writing this.
Generally it's OK to inherit an interface class multiple times, but you only want to inherit an implementation class once.
1) By not using virtual inheritance, or an equivalent scheme, a COM object may have more than one base class sub-object of type IUnknown, and this complicates the COM notion of object identity. Essentially it's resolved by providing a member function where client code can ask for an interface pointer of a specified interface, where IUnknown is required to be treated specially, always returning a pointer to identity-defining sub-object. Similar considerations of identity may apply for ordinary C++ interface inheritance.
Concerning design, there is nothing bad or particularly good about multiple inheritance with interface bases. If it is the most simple way to do what you need to do, do it.
The same goes for more complicated multiple inheritance. In C++, there is no need to avoid it, but you should know what you are doing if you use it. Even diamond shaped inheritance with a virtual base can be of use, but should not be used lightly. It tends to confuse your readers.

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.

What are real-world examples of C++ multiple inheritance? [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 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

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/