Alternative to direct inheritance - c++

I have two classes class A and class B. I want class B to have functionality of class A plus some more functionality of its own. One of the very simple ways to do this is to inherit class B from class A. But I cannot do this for some implementation specific reasons.
I have thought of another solution where in I will create another class class C which will contain all the virtual functions. The classes A and B will inherit from class C. The class A will contain the implementation of virtual functions and class B can also define the same set of functions and hence class B will have functionality of class A.
Is this the optimal solution? Are there any better solutions than this other than direct inheriting class B from class A?

What you are looking for is called Composition (over Inheritance).
Composition over inheritance (or Composite Reuse Principle) in
object-oriented programming is a technique by which classes may
achieve polymorphic behavior and code reuse by containing other
classes that implement the desired functionality instead of through
inheritance.
This means that instead of having class B inherit from class A, you can have class B contain an instance of class A. This is also good coding practice to avoid tight coupling between class A and class B.

You can do that however if you create class C to be an abstract base class and have class A and class B inheriting from it, then you realize that class A and class B would be unrelated except for the fact that they inherit from the same abstract base class. That means that you would not be able to cast instances of class B to A, etc. In general such implementation depends on the use cases.
E.g.:
Your class C is Person, class A is Teacher and class B is Student. Then a student is not a teacher and a teacher is not a student, so such implementation is valid.

You can use proxy classes, by creating two other classes PA and PB where PB inherits PA. These proxy classes duplicate the interface of A and B respective, but doesn't actually implement them. Instead they just call the functions in an instance of A and B.

The class A will contain the implementation of virtual functions and class B can also define the same set of functions
This way you'll have code-duplication and it's not a good thing.
If you don't want to use inheritance, try composition.
I explained composition earlier here.

Related

Is it a good practice in C++ to add members into abstract class that is an interface?

I need to write an abstract class that defines an interface.
All its methods are pure virtual ones.
Now, there are a few members that should be in that class as well, and my question -
is it a good c++ practice to add them in this class or should I define a new class (let's call it: class members) that contains those members, and the derived class will inherit from both: the interface class and the member class.
thanks

Inheritance vs Composition:: Is my understanding correct?

In composition, one class explicitly contains the other. However in Inheritance, the base class is implicitly contained in the derived class. Correct or not? I ask this because after several days of studying inheritance, it's only today that I got to read somewhere that an object of a derived class always contains an object of it's base class.
I mean, I thought that there would be only one object and just the functionality would be inherited but I didn't know that it would also contain an object of the base class within.
In Composition, one object contained another object. While in inheritance, your object is acquire properties of base class.
I mean, I thought that there would be only one object and just the
functionality would be inherited but I didn't know that it would also
contain an object of the base class within.
Yes you are right, there will be only one object and functionality is getting inherited. Even if your base class have member variables, there size will getting added to your object size.
You can directly call public and protected methods of base class. While in cointainership you are only able to access public methods.
That's should be:
In composition, one class explicitly contains an object of the other class. However in Inheritance, the base class is implicitly contained in the derived class.
In short:
Composition is about the relationship of class and object.
Inheritance is about the relationship of class and class.
And please remember "Prefer composition over inheritance".
Prefer composition over inheritance?
In general derived class contains all data members and shares the properties/methods of base class, but there is a difference between composition and inheritance.
By "composition" you mean that one object "has" some other object. In example: human has a liver. In class design it can be presented like below:
class Liver {};
class Human
{
public:
Human() {}
private:
Liver mLiver;
}
When talking about an inheritance, there are 2 options: public inheritance roughly says that one object "is" a kind of other object. In example: Human is a kind of living creature. It does not sound naturally to say that human "has" a living creature inside. Public inheritance is a way to go in such case:
class LivingCreature {};
class Human : public LivingCreature
{
public:
Human() {}
}
Other option is protected/private inheritance, which should be used to implement some object "in terms of" other object. Generally it can also be treated as kind of composition, but first approach is usually better.
Summarizing:
If you can say that one object "is" a kind of other, more general object: public inheritance is the best way to go,
If you can say that one object "has" other object: use composition.
Consider the code:
class Engine
{
//Some Code
};
class Vehicle
{
//Some Code
};
class Car:Vehicle
{
Engine engine;
//Some Code
};
In this case class Car inherits the class Vehicle. An object of the class Car doesn't contain an object Vehicle, rather it is an object of the class Vehicle (Inheritance). On the other hand it does contain an object of the class Engine(Composition).
The fact that you can access a parent's function with this comes from the fact that the Car object is a Vehicle not because it contains an Vehicle object.
In composition, one class explicitly contains the other. However in Inheritance, the base class is implicitly contained in the derived class. Correct or not?
It's entirely a matter of knowledge/perspective: if you're aware that inheritance means a base class instance will be embedded in the derived class then saying class Dervived : Base can be seen as explicitly requesting that, while if you're aware that defining a variable inside class X means it's a member variable that will be contained in instances of X, then that can be seen as explicit too.
I ask this because after several days of studying inheritance, it's only today that I got to read somewhere that an object of a derived class always contains an object of it's [sic] base class.
The distinction between actually containing a base class object vs. through some more unspecified/mysterious means being substitutable for a base class instance on occasion, isn't necessarily the most important thing when starting to learn about inheritance, so it's easy to imagine it isn't emphasised in all learning material.
I mean, I thought that there would be only one object and just the functionality would be inherited but I didn't know that it would also contain an object of the base class within.
At an implementation level, it's important that it actually contains a base class instance, so code compiled to handle base class objects can work equally well on derived class instances. The C++ Standard could have deemed it merely an embedded copy of base class content with identical binary layout while not an actual base class object, but then a huge amount of text in the Standard would have to be added to mention that the derived objects could be used in scenarios where a base class instance was acceptable. In other words, the distinction is somewhat arbitrary, but it's easier for everyone if it's both intuitive and lends itself naturally to simpler, more concise Standard wording.
Inheritance vs Composition:: Is my understanding correct?
Conceptual differences:
Inheritance:
In case of inheritance, derived class is sub-type of base class.
Meaning if you derive Dog from Animal, then Dog is Animal and
all* operations that can be performed on Animal can be performed on Dog.
Using private, protected and public inheritance, however, you can control who knows that Dog is Animal and who knows inner workings of Animal. In case of protected or private inheritance only Dog will know that it is Animal, but it won't be obvious from the outside.
Composition:
In case of composition one class is included into another.
a Car is not a Wheel. But it contains Wheel. So operations that work on Wheel will not work on a Car.
By declaring member variable of type Wheel as public, private or protected you can control who can access Car's Wheels.
I believe that is clear enough?
Implementation details:
In case of C++, members of base class are included into derived class. Also methods that existed in base class will be accessible in derived class - somewhere. Access specifiers private, public and protected AND inheritance type determine which methods are visible and where.
I thought that there would be only one object
It is one object.
In microsoft compiler and g++ objects are "merged" together, meaning that in case of:
struct Base{
int a;
};
strict Derived: public Base{
int b;
};
Derived internally will probably (would need to check C++ standard to be sure) have this layout.
strict Derived{
int a;
int c;
};
or
struct Derived{
Base _;
int c;
};
In case of multiple inheritance and diamond inheritance things will get more complicated and base class can be included multiple times.

multiple inheritance is convenient?

i want to implement an Algorithm class which uses some utility classes.
but one class may need member variable or function of other utility class. So instead of
composition is it better to use inheritance as below ?
class A{
public:
void setA(int var){ a = var;}
int a;
};
class B{
public:
void foo(int var){
if (var==1){
//bla bla...
}else{
//bik bik...
}
};
class Algo : public A , public B{
public :
void run(){
setA(1);
foo(a);
}
};
Your class Algo should only inherit from A and B if it is a true IS-A relationship to A and B. If you are just wanting to use functionality from A or B, consider composition instead (or at least private inheritance).
For example, if I want to create a class, and that class needs to do some logging, then my class HAS-A logger, but it's not the case that it IS-A logger. Thus I wouldn't want to inherit from logger, but use composition instead.
In your case it doesn't make sense to use inheritance because Algo isn't a A or B, it merely uses them.
Inheritance is meant to express an "is a" relationship and should adhere to the Liskov substitution principle. Can you say Algo is an A and Algo is a B? In general I feel it's a bad idea for a derived class to muck with the base classes private variables (you may set them as protected but they should probably be private). You can always write getters and setters. You can get into trouble with multiple inheritance in so many ways and I think your approach while convenient now will lead you to program in a less maintainable way. I try to reserve inheritance for when I need to treat classes polymorphically, in most other cases I prefer composition.
I like this concept of inheritance:
Commonly thought of as a way to "reuse existing code" by creating a new class that inherits from another existing class. This way you can extend the functionality of an existing class w/o touching the existing class's code. But Herb Sutter has a bit of a different take on the use of inheritance--"Inherit, not to reuse, but to be reused. Don't inherit publicly to reuse code (that exists in the base class); inherit publicly in order to be reused (by existing code that already uses base objects polymorphically)." [C++ Coding Standards, p. 64]. He also says "In correct inheritance, a derived class models a special case of a more general base concept." [ibid, p. 66]
http://cpp.strombergers.com/
so if you don't need to reuse code polymorphically, or to make more special case for base, better use a composition.
Don't pick inheritance over composition as long as you do not need polymorphism. In your case, as you don't have and virtual functions in classes A and B that needs to be changed in class Algo, composition may be a better design choice.

When to used derived class pointer and base class pointer

Can anyone help me, when i have to used base class and dervied class pointer.
It depends on why you're deriving. If it is for an OO implementation,
most of the time, you'll use pointers to the base class (which will
often by abstract) exclusively; you'll only use pointers to the derived
class if the derived class defines an extended interface. But
inheritance in C++ is a technique, and it is often used for other
purposes. (Think of an iterator class, which inherits from an
instantiation of std::iterator. This is not OO derivation, and
you'ld never use a pointer the the instance of std::iterator.)
I'll often make the distinction, using "derivation" for the OO concept,
and "inheritance" for the C++ technique. But this is in no way
standard, and terminology varies greatly, so you'll usually have to
start by figuring out what the author is talking about: OO design or C++
implementation. And you'll sometimes end up realizing that he doesn't
know himself; that he's confusing the two in his own mind. Inheritance
is the C++ language construct used to implement OO derivation, but this
language construct can be used for other things.
When you have more than one derived classes. and you don't know at compile time that which derived class will be instantiated at runtime. base class pointer is preferred over derived class pointer.
Use the derived class pointer when you want to use the derived class interface, or when you want to ensure that you're dealing with this particular implementation of the base class, or when you want to call a non-virtual function defined in the derived class.
In other circumstances, it doesn't matter.
Base class pointers are used when you have multiple derived classes but you want to abstract yourself from the derived class type. This can be very useful for example in situations like this:
class Animal {
Animal();
}
class Dog : public Animal {
Dog();
}
class Cat : public Animal {
Cat();
}
As you see, in this example you have a base class (Animal) and two derived classes (Cat and Dog). Lets say now that you're running a zoo (that only has Cats and Dogs :) ), and you need to keep up a list of your animals. You could just create two separate lists, one for Cats and another for Dogs. However, if you consider that Cats and Dogs are just Animals, you could create a list with pointers to Animals.
This way, by abstracting yourself from the derived class type, you can work with different derived classes by having a simple pointer to a base class.
Derived class pointers are completely different since they can only "represent" the derived class type.

difference between interface inheritance and implementation inheritance

I found those two terms in the book of Meyers, but what is the difference?
Interface inheritance is public inheritance, while implementation inheritance is private inheritance.
If class B publicly inherits from A, B is an A: it inherits the whole interface of A, and a (reference/pointer to) a B object can be automatically be upcasted to A, and used wherever an object of A is expected. However, if B privately inherits from A, B is-implemented-in-terms-of A: only the implementation of A is inherited, not its interface. Thus (references/pointers to) B objects can not be used in places where A objects are expected.
Update
To reflect on #Michal's comment, here are some links (based largely on googling "c++ implementation inheritance") to demonstrate the common usage of these terms in the context of C++:
C++ Design/Coding tips - Part 7
Interfaces
Uses and Abuses of Inheritance, Part 1
Implementation (or class) inheritance is when you separate a common part of implementation in the base class.
Interface inheritance is when you use virtual methods. It is intended to separate interface from implementation and minimize dependencies between program elements.
The major difference is interface is public inheritance and implementation is private inheritance.
The data members and method of the public and protected section will be inherited from base class to derived class in their respective access specifier in public inheritance.At the same time the object of derived class can access the data members of base class as the normal method.
The data members and methods of public and protected section will be inherited from base class to derived class in private access specifier
Here's the difference between the two types of inheritance according to "Taligent's Guide to Designing Programs".
Inheritance
There are two forms of inheritance in C++: type inheritance and implementation inheritance. In both forms of inheritance, a derived class can share or override behavior inherited from a base class. However, use type inheritance only when it is necessary for a derived class to inherit type information as well. The primary reason to inherit type information is to allow for polymorphism.
Express type inheritance by deriving a class from a public base class; express implementation inheritance by deriving a class from a private or protected base class.
More at:
https://root.cern/TaligentDocs/TaligentOnline/DocumentRoot/1.0/Docs/books/WM/WM_23.html