This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, February 17, 2023

Explain different types of inheritance with their syntax.

 In C++, inheritance is a mechanism that allows a class to inherit the properties of another class. There are four types of inheritance in C++:

1. Single Inheritance:
    Single inheritance is the most common type of inheritance. In this type of inheritance, a derived class inherits properties of only one base class. The syntax for single inheritance is as follows:

class Base {
    // Base class members
};
class Derived : public Base {
    // Derived class members
};

2. Multiple Inheritance:

In multiple inheritance, a derived class can inherit properties of more than one base class. The syntax for multiple inheritance is as follows:

class Base1 {
    // Base class 1 members
};

class Base2 {
    // Base class 2 members
};

class Derived : public Base1, public Base2 {
    // Derived class members
};

3. Hierarchical Inheritance:

In hierarchical inheritance, a single base class serves as a parent to multiple derived classes. The syntax for hierarchical inheritance is as follows:

class Base {
    // Base class members
};

class Derived1 : public Base {
    // Derived class 1 members
};

class Derived2 : public Base {
    // Derived class 2 members
};

4. Multilevel Inheritance:

In multilevel inheritance, a derived class can inherit from another derived class, which in turn is derived from a base class. The syntax for multilevel inheritance is as follows:

class Base {
    // Base class members
};

class Derived1 : public Base {
    // Derived class 1 members
};

class Derived2 : public Derived1 {
    // Derived class 2 members
};

These are the four types of inheritance in C++, each with its own syntax and use case..



No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget