Understanding the exposition of Alexandrescu about the weaknesses of 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 7 years ago.
Improve this question
UPDATE: I have asked a narrower question here.
On pages 6-7 of Modern C++ Design, Andrei Alexandrescu gives a very fundamental discussion of the strengths and weaknesses of two C++ language features -- multiple inheritance and templates -- with respect to building flexible designs. He concludes:
Now compare the list of drawbacks of multiple inheritance with the list of drawbacks of templates. Interestingly, multiple inheritance and templates foster complementary tradeoffs. Multiple inheritance has scarce mechanics; templates have rich mechanics. Multiple inheritance loses type information, which abounds in templates. Specialization of templates does not scale, but multiple inheritance scales quite nicely. You can provide only one default for a template member function, but you can write an unbounded number of base classes.
I can sense that what Andrei says here is very important, but I cannot really understand what is being said without any examples to illustrate the points. This question is asking to provide simple examples to illustrate these points (please continue reading).
To make the question more specific, I would like to ask to please focus on the weaknesses of multiple inheritance. This is what Andrei has to say about them (the text in square brackets is mine as per my understanding of the context):
In such a setting [i.e. multiple inheritance], [to build a flexible SmartPtr,] the user would build a multithreaded, reference-counted smart pointer class by inheriting some BaseSmartPtr class and two classes: MultiThreaded and RefCounted. Any experienced class designer knows
that such a naïve design does not work.
Analyzing the reasons why multiple inheritance fails to allow the creation of flexible
designs provides interesting ideas for reaching a sound solution. The problems with assembling
separate features by using multiple inheritance are as follows:
Mechanics. There is no boilerplate code to assemble the inherited components in a controlled
manner. The only tool that combines BaseSmartPtr, MultiThreaded, and RefCounted
is a language mechanism called multiple inheritance. The language applies
simple superposition in combining the base classes and establishes a set of simple rules
for accessing their members. This is unacceptable except for the simplest cases. Most
of the time, you need to orchestrate the workings of the inherited classes carefully to
obtain the desired behavior.
Type information. The base classes do not have enough type information to carry on
their tasks. For example, imagine you try to implement deep copy for your smart
pointer class by deriving from a DeepCopy base class. But what interface would DeepCopy
have? It must create objects of a type it doesn’t knowyet.
State manipulation. Various behavioral aspects implemented with base classes must manipulate
the same state. This means that they must use virtual inheritance to inherit a
base class that holds the state. This complicates the design and makes it more rigid because
the premise was that user classes inherit library classes, not vice versa.
I would very much appreciate a simple example for each of the three items above. Each example would show both one limitation of multiple inheritance (e.g. poor mechanics) and how templates do not possess this limitation (Andrei wrote that "multiple inheritance and templates foster complementary tradeoffs").

Related

Are interfaces a good practice 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 3 years ago.
Improve this question
Coming from a Java/python world with little or no C++ experience, I am used to work with interfaces to separate the contract that a class has from its implementation, for the sake of the Liskov substitution principle and dependency injection.
I am not going to go over all the benefits of interfaces in Java, or why they were introduced (lack of multiple inheritance) and not needed in C++ (see here for example).
I also found out how to have the equivalent of a Java interface in C++
My question is more about whether or not this is a good practice in a C++ environment.
As I understand it, there cannot be the equivalent of an interface without pure virtual methods. This means that bringing interfaces in C++ will introduce some overhead in the code (because virtual methods introduce an overhead).
Therefore, are interfaces based on pure virtual method a good thing? Is there maybe some other way to achieve the Liskov Substitution principle and dependency injection that I don't know of? using templates maybe?
For example, google test has it easy to mock virtual methods, but proposes a way of mocking non virtual methods.
I am trying to figure out if my coding habits are still relevant in my new C++ environment, or if I should adapt and change my paradigms.
[EDIT based on answers and comments]
I got part of the answer I was looking for (i.e. "yes/no with arguments"), and i guess I should clarify a bit more what I am still trying to figure out
Are there alternatives to using an interface-like design to do dependency injection?
Reversing the question: should one decide to go for an interface-based design, except when speed is absolutely crucial, when would one NOT want to do an interface based on pure virtual methods?
Notes:
I guess I'm trying to figure out if I'm too narrow minded thinking in terms of interfaces (hence my edit looking for alternatives).
I work in a C++ 11 environment
I would say interfaces are still a fine practice in C++. The overhead that virtual methods introduce is minimal, and as you will hear time and time again, premature optimization is a big mistake. Abstract base classes are a well-known, well-understood concept in C++ and favoring readable, common concepts over convoluted template metaprogramming can help you immensely in the long run.
That being said, I would try to avoid multiple inheritance. There are certain tricky issues that come with it, which is why Java explicitly forbids it for regular inheritance. A simple google search can give you more explanation.
If you have multiple unrelated classes and you'd like to call a method of the same name (let's say foo()) on each of them, then instead of an interface you can make a templatized function to do this.
class A {
void foo() {
// do something
}
};
class B {
void foo() {
// do something
}
};
template <typename T>
void callFoo(const T& object) {
object.foo();
}
int main() {
A a;
B b;
callFoo(a);
callFoo(b);
return 0;
}
Even though there is no explicit "contract" in callFoo() stating that the type must support .foo(), any object that you pass to it must support it or there will be a compile error. This is a commonly used way to duck-type objects at compile time and an alternative to interfaces for certain scenarios.
At the end of the day, as you learn more C++, you will use your own judgement to decide how you will accomplish the polymorphic behavior you want. There is no single right answer how to do it, just as there is no wrong answer either. Both abstract base classes and template duck typing are good tools that serve slightly different purposes.

Implement concatenative inheritance in C++

Is it ppssible to implement a concatenative inheritance or at least mixins in C++?
It feels like it is impossible to do in C++, but I cannot prove it.
Thank you.
According to this article:
Concatenative inheritance is the process of combining the properties
of one or more source objects into a new destination object.
Are we speaking of class inheritance ?
This is the basic way public inheritance works in C++. Thanks to multiple inheritance, you can even combine several base classes.
There might be some constraints however (e.g. name conflicts between different sources have to be addressed, depending on use case you might need virtual functions, and there might be the need to create explicitly a combined constructors).
Or is inheritance from instantiated objects meant ?
If it's really about objects and not classes, the story is different. You cannot clone and combine object of random type with each other, since C++ is a strongly typed language.
But first, let's correct the misleading wording. It's not really about concatenative inheritance, since inheritance is for classes. It's rather "concatenative prototyping", since you create new objects by taking over values and behaviors of existing objects.
To realize some kind of "concatenative prototyping" in C++, you therefore need to design it, based on the principle of composition, using a set of well defined "concatenable" (i.e. composable) base classes. This can be achieved, using the prototype design pattern together with the entity-component-system architecture.
What's the purpose
You are currently looking for this kind of construct, probably because you used it heavily in a dynamically typed language.
So keep in mind the popular quote (Mark Twain ? Maslow ? ):
If you have a hammer in your hand, every problem looks like nails
So the question is what you are really looking for and what problem you intend to solve. IMHO, it cannot be excluded that other idioms could be more suitable in the C++ world to achieve the same objective.

What is the difference between abstraction and interface? [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 6 years ago.
Improve this question
I found the following definitions from the internet and both sound similar to me :
Abstraction : Abstraction is another good feature of OOPS. Abstraction means to show only the necessary details to the client of the object. Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT. When you change the gear of your vehicle are you really concern about the inner details of your vehicle engine? No but what matter to you is that Gear must get changed that’s it!! This is abstraction; show only the details which matter to the user.
Let’s say you have a method "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member, Right?
So abstraction says expose only the details which are concern with the user (client) of your object. So the client who is using your class need not to be aware of the inner details like how you class do the operations? He needs to know just few details. This certainly helps in reusability of the code.
Interface : An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X". Again, as an example, anything that "ACTS LIKE" a light, should have a turn_on() method and a turn_off() method. The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T (whatever the interface is ) must have functions called X,Y,Z, etc.
Interfaces in Object Oriented Programming Languages
An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a scooter class and a truck class. Each of these three classes should have a start_engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that they must have a start_engine action is the domain of the interface.
Doesn't both the explanations say the same thing? So are they same or different?
An interface tells you what you can do with something. Abstract(ion) might additionally tell you how you do some of these. Thus an interface is always a kind of abstraction, but an abstraction can carry more information than an interface.
In C++-world, unlike e.g. Java, there's no explicit declaration of an interface; instead, your class automatically provides all the interfaces that the base classes provide. Some of us tend to call classes with only pure virtual methods (and, possibly, a non-pure virtual destructor) and interface. Note that, strictly speaking, it's not the only way do specify an interface and new/upcoming C++ features (like Concepts) will likely change this scene. Similarly we usually say that a class is abstract when it has at least one pure virtual method, albeit there might be different definitions when you use template/traits based composition and fulfilling and interface instead of virtuals and inheritance for the same.
Abstraction is to move away from the details, to 'zoom out', if you will. You tend to abstract away from the implementation by creating structures to lay out your code. As an example, rather than thinking in terms of individual cells in a body, you could abstract away to thinking about the person as a whole, or go even further and think about groups of people.
An interface is just that; how you interface with your code. This is normally in the form of public functions in your classes, though not necessarily. Ideally, the interface should describe what something can do, without being affected by how it does it. For example, you might have a function to get a person to walk, but not one to move their individual muscles.
In the context of , say, a C++ function:
The interface describes how a feature is used which is what a function prototype does.
A client calling the function need not worry how the function is implemented (ie how it go about doing things). In short you have a layer of abstraction.

What are the benfits of inheritance over template based data structures? [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 9 years ago.
Improve this question
I'll get to the point and explain below.
What, if any, are the benefits of...
template<class T>
class myStack : public myList<T>...// my stack
over
template<class T, Container = deque<T> >
class stack...// C++ stack
Recently I was writing some code and was faced with an inheritance issue where I was exposing aspects of the base class that I would rather not. The specific example isn't important so I'll relate it to few semesters ago when I took a data structures class where we implemented our own list, stack, queue and others.
In this class we were to design a stack which was to inherit from a list. The problem with this was I was exposing public methods of the base that could potentially damage the stack's integrity. It may be that I'm a bit of a purist but having the insert() and remove() lying around in the stack was bothersome for me. I didn't have time to investigate it then but this time I thought I would consult the C++ standard to see how the stack was defined there. Low and behold I found the code above; it was an obvious solution that I overlooked.
Here's my view...
The C++ implementation is "better" because it allows the user the freedom to choose the underlying structure if desired and maintains a more pure stack in that it is clear only stack functionality available to the user and can be more guarded from unintended corruption. Are there more substantial, non-subjective reasoning behind the design choice, or inherit flaws in it?
The obvious benefit of mine is code re-use which is par for the course, I don't see that as an additional benefit the way I personally see the benefit of the freedom with the C++ implementation. I do see the over exposure (my words) of the base class as a con though. Are there more substantial, non-subjective reasoning behind the design choice, or inherit flaws in it?
Again, I'm not concerned with languages, I'm more concerned with weighing the pros/cons for my own designs.
C++ collections and Java collections are very different. Java collections have an obvious type hierarchy, whereas most C++ collection types do not extend any other class, and templates are extensively used to support multiple collection types.
Although I don't know for sure, I imagine that the Java library developers made Stack a subclass of Vector because a stack is a collection of elements in a well defined order, so acts like a list, and by subclassing Vector they could get most of the implementation of the stack for free. This also has the benefit that you can use stacks in places where you need a list or a vector, for example you could pass a stack to a function that takes a list and iterates over it. Of course, c++ stacks are not iterable, so there is (intentianal or not) a very different semantics between the two stacks.
Finally, for your own code, if you are considering whether B should inherit or contain A, first ask yourself if B is an A, or more specifically, if you would ever want to treat a B as an A by passing it to a function that expects an A, or returning it from a function that needs to return an A. If so you should use inheritance, otherwise you should probably use composition.
The Stack class, as well as Vector, are legacy containers. They are left-overs of JDK1.0, they are based on an older design of the utils library, and are inefficient because of synchronization.
The preferred implementation of Stack in Java is given by implementations of the Deque interface (mainly ArrayDeque and LinkedList). You get the difference: in C++ one says that an stack has a given implementation. In Java one declares a class implementing the desired interface:
class ArrayDeque<E> extends AbstractCollection<E>
implements Collection<E>, Deque<E>, Queue<E> //etc
When using such classes, always take the less specialized interface possible, for instance:
Deque<String> stack = new LinkedList<String>();

Does the inheritance of opencv functions make my program better? [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 8 years ago.
Improve this question
I have a program that uses opencv functions such as calibratecamera. Now I am working on the final version of my code, and I was wondering if instead of calling opencv's functions I inherit them in my classes would make my program 'better' ?
As pointed out in the comments, your question is very "general" and somehow confused. However, there is a general answer to the question "is it better to inherit?". Of course, being a general answer, it is oversimplified and might not apply to your case.
Item 58 in "C++ Coding Standards" (Sutter, Alexandrescu), is titled
Prefer composition to inheritance
You can find similar advice in several other books too.
The reason they give for making their case is:
Avoid inheritance taxes: Inheritance is the second-tightest coupling relationship in
C++, second only to friendship. Tight coupling is undesirable and should be
avoided where possible. Therefore, prefer composition to inheritance unless you
know that the latter truly benefits your design.
So, the general advise is to try and avoid inheritance as much as possible, and always being conservative on using it, unless you have a very strong case for it. For instance, you have a case for the use of public inheritance if you are modelling the so called "is-a" relationship. On the other hand, you have a case for using nonpublic inheritance if you are in one of the following situations:
If you need to override a virtual function
If you need access to a protected member
or in other less frequent cases.
Whatever your final choice is, be sure to only inherit from classes that have been designed in order to be base classes. For instance, be sure that the base class destructor is virtual. As the cited book poses it:
Using a standalone class as a base is a serious design error and
should be avoided. To add behavior, prefer to add nonmem-ber
functions instead of member functions (see Item 44). To add state,
prefer composition instead of inheritance (see Item 34). Avoid
inheriting from concrete base classes
OpenCV is a library with well defined API. If you have an existing application that uses functions bundled within this library and you don't have a valid reason for adding an additional functionality to them, there is no advantage that you could gain by wrapping them.
If you want to change the interface because you think it will make your code cleaner, I would worry about the maintenance in case the API will change in the future.
While changing the design of your applications, your decisions should be based on specific reasons. "I want to make my program better" is too abstract one.