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.
Related
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 5 years ago.
Improve this question
I am pretty new to both the OOP and the C++ language.
Recently I have been given the task of come up with an object oriented design -which I guess I have done quite ok so far considering my lack of knowledge on the subject. And since I want to keep performing either like I have done so far or better, I want to get my doubt cleared.
I made a design in which the base class offers two virtual functions. Some children implements both virtual functions of their parent, but some others implement only one.
Now, I know that it is not the best / clean design somebody can come up with, and that if I do not implement (in some children) one of these virtual methods I might get warnings from the compiler. I know I can implement the methods, and when they are not needed they could simply return an exception, or simply do nothing.
With all that said, my doubt/question is: What is the actual risk of not implementing one of these virtual methods in the children? What happens on the object which does not have a virtual method's implementation of its parent? I am looking for a rather deep insight - I mean, I am looking for an understanding on a object's guts level so to say.
If an explanation is not possible to be given, any reference where to possible look at will be equally Welcomed and appreciated.
Cheers!
EDIT
Hi. Thanks everyone for your answers. My initial question -at least in my head- was not related to "Possible duplicate" suggested by Viktor Chvátal - but this question he pointed at, ALONG WITH all the other answers to my question clarified and dissipated my doubt. At the beginning, I though that if child does not implement the virtual method from parent, there would be some sort of "hole" there, where a method (or pointer to method, or whatever) should be. But then what would happen is that the child would be using the parent's implementation.
Thanks everyone and sorry for the fuss of asking something which is apparently already answered somewhere else. The thing is I should read more about how stuff works, before giving somebody else's comments as granted - wich is what took me to ask this question in the first place.
I'll try no to repeat this mistake in the future.
That is not the correct question to be asking. The correct question is if the child class only overrides one or two of the functions it is allowed to override then the question is "Should my child class be deriving from the parent class". For example of a bad inheritance is:
class shape
{
public:
virtual void draw();
virtual void print();
};
class log : public shape
{
public:
void print() override;
};
This is a bad inheritance as the two both need a print method but a log class has nothing to do with drawing nor is it related to a shape. Is it dangerous not in the context of security but in the sense that anyone using your code will be extremely confused it is.
An example of a better inheritance would be:
class shape
{
public:
virtual void draw() = 0;
};
class rectangle : public shape
{
virtual void draw();
};
Here square inherits from shape as a rectangle is a shape and the inheritance enforces rectangle to define a draw method. With this inheritance it is very clear as to what is going on and there is no risk involved.
Some children implements both virtual functions of their parent, but
some others implement only one
That is perfectly fine, and that's one of the reasons virtual methods differ from abstract ones, former being optional to be overridden in more specific types (child classes).
I know I can implement the methods, and when they are not needed they
could simply return an exception, or simply do nothing
Throwing exception, say not implemeted or supported, is bad idea. If you knew the specific type would not support specific behavior, that behavior should not be part of base class itself. You should implement such behaviors (which are specific to some derived classes) using interfaces instead.
You might be confusing virtual methods with pure virtual methods.
A virtual method is just a regular method that children classes can override, which means "swap the default behavior for a custom one".
You declare them like this:
virtual ReturnType myVirtualMethod();
Pure virtual methods, on the other hand require you to implement them in the child class. They are used when no sensible default behavior can be written within the parent class. In case you don't implement them, the child class will fail to compile, which is good, because it prevents undefined behavior - in this case: what should run when NO method was provided? It is impossible for the compiler to decide.
They can be declared with this syntax:
virtual ReturnType myVirtualMethod() = 0; // notice the "= 0" at the end
So I think the question you should ask yourself is this one: "can I provide any default behavior that works in most cases for this method?" If not, you should consider making the method pure virtual, otherwise implement the default behavior in the parent class, and don't bother overriding that method in child classes that don't need it.
Hope this helped!
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 have searched on google and here but I can not understand why a pure function in a class must be virtual. I understand maybe it is not very useful declare a "normal function" as pure but I don't think is a nonsense. I mean, the word "pure" is there just to declare an abstract class. Ok, I can not use polymorphism with that pure normal function but the main reason (declare a class as abstract) is reached anyway.
Am I wrong?
There is no requirement that a pure function be virtual. If you're thinking of the term "pure virtual function", "pure" applies to "virtual" there; the function is purely virtual. It's a different use of the word "pure".
I mean, the word "pure" is there just to declare an abstract class.
It's not. The reason for declaring a pure virtual function is not to prevent instantiation of the enclosing class; it's to ensure that concrete subclasses implement the method, usually because the abstract class cannot provide a reasonable implementation.
Ok, I can not use polymorphism with that pure normal function but the main reason (declare a class as abstract) is reached anyway.
If you're looking for a way to declare a class abstract without any pure virtual functions, C++ does not have dedicated syntax for that. The suggestions I've seen are to declare and implement a pure virtual destructor (you can do that), or to make the constructor protected (but making the constructor protected won't make your class pass std::is_abstract). In any case, it wouldn't make much sense to attach the syntax for that to arbitrary member functions; something like class Foo = 0 { ... }; would make more sense.
The only reason you'd want to have a "pure function" is to make sure subclasses that inherit from this class define an implementation of this function. If you would allow pure functions to be non-virtual and thus not being able to be overriden they are basically pointless to have.
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.
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.
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