Does the inheritance of opencv functions make my program better? [closed] - c++

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.

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.

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.

Pros and cons for pure virtual c++ coding [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 7 years ago.
Improve this question
I'm coming form java background, had a conversation today with one of our C++ developer regarding to convert an existing code to have a pure virtual methods (interface) and to use them as dependency injection all over the code for better decoupling.
He tried to convince me that we should use them only when there is a "logic" in the code and in case the code is just collecting information from the PC it is not necessary.
Long story short, I'm looking for good reasons why to refactor the code and use IoC and pure virtual method instead of leaving the working coupled code as is.
There are many reasons why you should or should not refactor existing code. Each situation is unique. If you are talking about some kind of project with large codebase and you want to refactor it's core which works good and properly tested than in 99% cases I'd recomend you don't do that. You can add more bugs to tested code without making really needed improvements.
If code is just collecting some information you can extract interface for testing class that uses this object. If you don't use unit tests for some reasons than leave it as it is.
Overall you oponent is probably right, make interfaces when you really need them and write clean code with easy dependency extraction.
Why use pure-virtual methods?
I try to write base class functions to provide default behaviour for all the interface methods. I am surprised by how often these defaults simply generate some error handling (using the locally accepted mechanism).
For one example, I worked on code that received commands to set led states. During development, the 'other software' sometimes would (mistakenly) request a colour explicitly dis-allowed by the requirements. ('Red' disallowed on status led 5) My default functions generated the appropriate error message, and identified which 'other software' sent the erroneous request.
There are also cases that in some way have no appropriate default behaviour. For these situations, I create pure-virtual methods. Declaring the method pure virtual is documenting the idea that the base class will not provide the functionality, and is therefore requiring that all derived class must provide some code to support this concept.
"A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class that is not abstract" - Wikipedia
good reasons why to refactor the code?
Readability.

Understanding the exposition of Alexandrescu about the weaknesses of 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 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").

Should classes with public non-virtual destructors be marked "final"? [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 7 years ago.
Improve this question
To close voters, please help me improve the question so it gets reopened: How can I improve this question so that it gets reopened?
Herb Sutter wrote:
A base class destructor should be either public and virtual, or
protected and nonvirtual.
According to that guideline, if you have a class with a public non-virtual destructor, then that class shouldn't be used as a base class.
Why not mark it final to enforce that?
But Sutter also wrote the following, implying that final need not be used:
Re "uses of final are rarer" - well, they sort of are. I don’t know
of many, and during standardization Bjarne repeatedly asked for
examples of problems it solved and patterns where it should be used,
and I don’t recall any major ones that stood out.
Another relevant quote, implying that final should be used now that it's available, is from Scott Meyer's Effective C++, item 7:
If you're ever tempted to inherit from a standard container or any
other class with a non-virtual destructor, resist the temptation!
(Unfortunately, C++ offers no derivation-prevention mechanism akin to
Java's final classes or C#'s sealed classes.)
Another data point is that the standard library has no types marked "final", but the reason for that seems to be to avoid breaking code.
There's a similar question here, but not exactly a duplicate as it misses the "protected, nonvirtual" option: Default to making classes either `final` or give them a virtual destructor?
According to that guideline, if you have a class with a public non-virtual destructor, then that class shouldn't be used as a base class. Why not mark it final to enforce that?
Because it's a guideline that fits in certain situations, but not all, so why would you "enforce" it?
It's all very well and good disallowing inheritance where dynamic polymorphism through virtual function calls has not been provisioned, but that's not the only scenario in which we use inheritance.
C++ is multi-paradigm and it doesn't make sense to start enforcing narrow approaches that fit only a subset of use cases. Your suggestion, from what I can tell, essentially boils down to prohibiting people from using inheritance unless they're also going to use dynamic polymorphism.
I routinely declare classes as final unless they are
intended to be used as base classes or
POD types.
I think it is a good thing to explicitly design for inheritance (which should be used sparingly after all). And if I didn't bother designing a class as a base class, I document this by declaring it final. If later I find that it would be useful to derive from that class, having to go and remove the final is a good opportunity to also check that the other conditions for making it a viable base class are met.
I usually don't declare POD types as final because I don't see any benefit in doing so and deriving from them is sometimes useful to utilize the empty base optimization.