How to declare and assign Derived classes in C++

In this tutorial, we will see how to declare the derived classes from the Base class in C++. To make this more clear and understandable, first, let us know more about the base class and the derived class. These topics come under the topic of inheritance.  The created new class will have the properties of the existing class.

Derived class in C++

First, let us know about the base class. A base class is a class from which the derived class are derived. And the derived class is the new class that is created from the base class.

Deriving classes from existing classes

Syntax

class Base_class{
//Base class members will be there
};
class Derived_class : access specifier Base_class{
// Derived class members will be written here.
};

The access specifier can be public, private, or protected. By default, it will be private if nothing is mentioned. Here in the above code, the base class is named as Base_class and the derived class is named as Derived _class.

Example:

#include<iostream>
using namespace std;
class Base_class{
public:
int a;
};
class Derived_class : public Base_class{
public :
int b;
};
int main()
{
Derived_class object;
object.b =10;
object.a =20;
cout<<"Int value of Base class(a) is " <<object.a <<endl;
cout<<"Int value of Derived class(b) is "<<object.b <<endl;
return 0;
}

The output of the above code will be

Int value of Base class(a) is 20

Int value of Derived class(b) is 10

Hope you liked the Tutorial.

Leave a Reply

Your email address will not be published.