How expensive or costly is inheritance in C++ [duplicate]
Possible Duplicate:
Private/protected inheritance What is the cost of inheritance?
I am sorry if this question is a duplicate. I have a C++ class say A, which has some methods , out of which I am interested only in one method. I need to implement a new class B , which has got same data members as that of A. I don't want everything of A in B but that one method ( or may be a couple ) . B should strictly implement a new operation X , but should not expose anything what A has been doing.
So does it make sense to inherit B from A? How expensive is this in terms of memory footprint , performance ? Will it be sensible if I duplicate that one method from A to B , without inheriting B from A? What other alternatives do I have?开发者_开发技巧
A common missunderstanding in OO design is that inheritance is a normal or good thing to do in most situations. Inheritance is good when you need to override certain operations of the base class but keep the same interface.
Take a look at other design patterns, composition etc that might be a better fit for you and still make it possible to reuse code.
class B
{
public:
void X()
{
m_a.Y();
}
private:
A m_a;
}
If B inherits publicly from A, you are saying that a B is an A, i.e., that whatever you can do with an A, you should also be able to do with a B. If you don't want all of A's behaviour available in a B, then public inheritance isn't the way to go.
Most likely, you want a simple containment relationship, whereby B contains or references an A and calls the reused member function (they're not called methods in C++).
Maybe alternative is composition. Inheritance is good solution to explain relation "is a". If I good understand, you need only one method (more precisly, body of that method). So maybe solution for your problem is that class B contain instance of class A, and internaly after call method B::Foo(), then
void B::Foo()
{
_a.Foo();
}
Inheritance is not good solution in this case.
To answer your main question about how costly inheritance is: In regards to performance, a method call is not more expensive when the method is inherited, as long as the method is non-virtual. In regards to memory footprint inheritance is also not more expensive than aggregation, in both cases, the fields of the aggregate member or the fields of the inherited base class will be lied out in memory with the fields defined in the new class you write.
So, as everyone else pointed out, your decision whether to use inheritance or aggregation/composition should not be based on any performance/cost measures, but on whether you really need an is-a relationship or not.
精彩评论