How to define inheritance in C++?

Introduction to inheritance

How to define inheritance in C++? what are the applications of using it? Inheritance is one of the most significant feature of object oriented programming. It is the process of creating a new class also called the derived class from the parent class also known as the base class. The derived class has all the characteristics of the base class but it can also have its own features as well. The base class in not effected by this procedure. The following picture shows the inheritance concept.

inheritance
inheritance

Example of inheritance

class Counter1
{
protected:
unsigned int count1;
public:
Counter1() : count1(0)
{ }
Counter1(int c2) : count1(c2)
{ }
unsigned int get_count1() const
{ return count1; }
Counter1 operator ++ ()
{ return Counter1(++count1); }
};

class CountDn : public Counter1
{
public:
Counter1 operator — ()
{ return Counter1(–count1); }
};
int main()
{
CountDn c1;
cout << “\nc1=” << c1.get_count();
++c1; ++c1; ++c1;
cout << “\nc1=” << c1.get_count();
–c1; –c1;
cout << “\nc1=” << c1.get_count();
cout << endl;
return 0;
}

graphical depiction of inheritance example
graphical depiction of inheritance example

Note here the arrow is pointing upward indicating that the derived class has access to its base class. The base class can not access the derived class. It only transfers its characteristics to the derived class. This is also called DAG (directed acyclic graph).

Inheritance and accessibility

accessibility during inheritance
accessibility during inheritance
access specifier in inheritance
access specifier in inheritance

It can be noticed that if we want any class to act as a base class then all the properties we want to transfer to the derived class should be declared under header protected. If we declare the class members under private header, then we will not be able to access those members.

You should realize that there’s an impediment to making class individuals ensured. Let’s assume you’ve composed a class library, which you’re circulating to people in general. Any developer who purchases this library can get to ensured individuals from your classes essentially by getting different classes from them. This makes secured individuals impressively less secure than private individuals. To stay away from defiled information, it’s frequently more secure to power determined classes to get to information in the base class utilizing just open capacities in the base class, similarly as normal fundamental() programs should do. Utilizing the ensured specifier prompts less difficult programming, so we depend on it

Also read here:

https://eevibes.com/how-do-you-define-classes-and-objects-in-c/

How do you define classes and objects in C++?

Leave a Reply

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