Open In App

How to Create a Derived Class from a Base Class in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, one of the fundamental concepts of Object Oriented Programming (OOPS) is inheritance, allowing users to create new classes based on existing classes. The class that inherits another class is called derived class and the class that is inherited is called base class. In this article, we will learn how to create a derived class from a base class in C++.

Create a Derived Class in C++

We can use the concept of inheritance in C++ which is a process in which one object acquires all the properties and behaviors of its parent object automatically. Using this, we can create a new class from an existing class where the existing class is the base class (or parent class), and the new class is the derived class (or child class).

Syntax to Inherit a Class

class BaseClass_Name{
//body of class
};

class DerivedClass_Name : access-specifier Baseclass_Name{
//body of class
};

Here, the access specifier assigns accessibility of the base class members in the derived class. For example, if the access specifier is private, then all the members of the base class will be private in the derived class.

C++ Program to Create a Derived Class from a Base Class

The following program illustrates how we can create a derived class from a base class in C++.

C++
// C++ Program to illustrate how to create a derived class
// from a base class
#include <iostream>
using namespace std;

// Base class
class Base {
public:
    // Base class method
    void basePrint()
    {
        cout << "Method of Base class called" << endl;
    }
};

// Creating a derived class from base class
class Derived : public Base {
public:
    // Derived class method
    void derivedPrint()
    {
        cout << "Method of Derived class called" << endl;
    }
};

int main()
{
    // creating an object of derived class
    Derived obj2;
    // calling function of base class using an object of
    // derived class
    obj2.basePrint();
    // calling function of derived class
    obj2.derivedPrint();
    return 0;
}

Output
Method of Base class called
Method of Derived class called

Time Complexity: O(1)
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads