Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a baseclass with some private members that have the same type for every subclass. Every subclass has his own members (some more than others). I store pointers in a list of baseclass* type to every subclass member.
So I could use virtual functions to call public members of my subclass. But In some subclasses I won't have functions to replace.(But I don't think that's a problem unless I try to call it to a certain subclasses)
The other method is to dynamic cast the the pointer from a baseclass to the right subclass and call his members.
How would you do it? Why would I do one method instead of the other?
Need to use dynamic_cast usually suggests a flaw in design (or need to conform to some external constraints). So you should design so that you don't need it.
You use a base interface when you're handling different types of objects in some uniform way. This means the base interface should be complete enough to provide all operations you will want to perform in such case. If some operations don't make sense for some subclasses, there are two possible scenarios:
The operation is a no-op for the subclass, but it still forms a part of how the class is to be used. In such case, just implement the subclass function as empty.
The operation makes no sense whatsoever for the subclass. In that case, it should probably not be part of the base interface, and more importantly, it shouldn't be needed there. If you need a subclass-specific functionality, you probably don't need it when handling a generic collection. That's what your design should ensure.
It seems you want to use virtual functions assuming you have heterogeneous sequences of you objects: using dynamic_cast<>() tends to be quite slow and if you don't know the type of your objects you'll need to cast a lot.
Note that for using objects data members actually shall not matter! You look at the object through its publuc functions. Data members are normally all private (there are very few exceptions and these are only borderline data, e.g., a registry for event handlers may be a public data member).
Related
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.
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.
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
What is the difference between wrappers and adapters?
Since they both wrap around another object and provide additional functionallity why are there two separate names?
Also the STL smart pointers are wrappers or adapters?
Wrappers typically store a primitive type and add operations that the type does not support / support poorly-erroneously.
Adapters are used when the interface of a class is not exactly what is needed and provide a wrapping effect while changing the interface.
A way to distinguish the two, is that often an adapter is implemented by private inheritance. This kind of implementation is not usually available for wrappers that wrap a primitive.
Based on this I would call smart pointers wrappes
It is almost the same. The only difference is that if your class provides new interface with the same (or almost the same) functionality as base one it is better to call it adapter.
If you class adds some new functionality (for example some additional processing of base class output) it is better to call it wrapper.
Smart pointers are wrappers because they add additional functionality (reference counting) to base class.
The word "wrapper" is extremely overloaded in software engineering. You use it when you don't want to (or cannot) be more specific. Basically, every time you add an additional layer around something so that this "something" cannot (or should not) be accessed directly anymore, you "wrap" it, whatever the reason may be. The wrapped component may be too low-level, it may be incomplete, you may want to add caching to it, you may simply want to reduce compile time... or whatever reason you can think of. The word "wrapper" alone does not tell you more than that.
Therefore, nobody will object when you say that a smart pointer is a wrapper around a raw pointer. A smart pointer prevents direct access to the raw pointer (or allows it if you need to but reminds you that you should not do it normally). That makes it a wrapper.
"Adapter" is a slightly more specific word. It means that a software component has exactly the features you need but exposes them in a formally wrong way, so you add a layer around the original component just to make its interface conform to your needs. Adapting something is a special case of wrapping. I would not call a smart pointer an adapter. "Adapting" implies that the functionality is basically unchanged but only the names and formalities of the interface are different -- which is not true for smart pointers.
Summary:
"Wrapper" = Adding a layer around a software component for any reason.
"Adapter" = Wrapping with the reason being nothing more than an incompatible
interface.
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>();
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.