types of inheritance in c plus plus c++

Posted under C++ Course On By mohammed.mutawe

types of inheritance in c plus plus

inheritance is a science of class objects, enabling us to use ClassApp, and giving its characteristics to child class, and this is called genetics in programming languages.

 

Brief

Away from inheritance idiomatically, but it performs exactly the same function in programming languages ​​as well. Imagine that Mercedes, for example, made a completely new vehicle and put all its components from the steering wheel, tires, interior cabin and lights.

Then it re-cloned that vehicle for another vehicle in its factory, but with more additions such as precious aluminum wheels, electric windows, and road simulation system while retaining the most important characteristics of Mercedes such as the logo, brand, design style and engine mechanism, this process is called the inheritance of manufacture.

And this is how programming languages ​​work, we define certain variables and functions in the parent class, and then we preserve them when inheriting child with the addition of some additional functions, for example, or variables.

 

Definition

This code shows the general form of inheritance, more than two classes can be inherited, but to simplify the understanding, we will only mention one type of inheritance in this lesson. The code.

//parent
class Parent
{
public:

};

// Child
class Child : public Parent  //mention parent class after defenition of child directly
{
public:

};

 

As we mentioned earlier, child class carries the characteristics of parent in addition to his own characteristics, and we can observe the success of the inheritance process when calling the class functions inside the Main function.

 

Example

Please, to understand the inheritance well, copy the following codes into your code editor.

#include<iostream>
    using namespace std;

    class parent {

    protected:

    int count;

    public:
    parent() {
    count = 0;
    }
    parent(int c) {
    count = c;
    }
    int get_count() {
    return count;
    }

    int callParent()
    {
    int val = 20;
    return val;
    }

    };

    class child :public parent {
    public:
    child() :parent() {}
    child(int c) :parent(c) {}          // there is constructors when inherts parent properties

    int callChild()
    {
    int val = 10;
    return val;
    }

    };


    int main() {

    child innherts(100);



    cout << "I will call child function : " << innherts.callChild() << endl;
    cout << "I will call parent function : " << innherts.callParent() << endl;
    cout << "I will return count from parent : " << innherts.get_count() << endl;


    return 0;
    }

 

Leave a comment

Your email address will not be published. Required fields are marked *