Single Inheritance And Its C++ Program - Coding Bot

Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Saturday, 25 May 2013

Single Inheritance And Its C++ Program

Hello Guys,
As I have already discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its first type, that is, Single Inheritance.

In Object Oriented Programming, the root meaning of inheritance is to establish a relationship between objects. In Inheritance, classes can inherit behavior and attributes from pre-existing classes, called Base Classes or Parent Classes.The resulting classes are known as derived classes or child classes

There are 5 types of Inheritances used in C++:

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchial Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance


So in Single Inheritance, we have one base class and one child class. It means that, there is only one child class, which is inheriting attributes and behavior from only one base class, as shown below:


Types Of Inheritance

Let us consider a simple example to illustrate Single Inheritance. The following program shows a base class 'B' and a derived class 'D'. Both have a private data member each, integer 'a' and integer 'c' respectively. Base class has a function to assign values to its data members. Derived class inherits from base class and its function then calls data members from base class. Then the logical operation is performed and the result is displayed.

C++ Program For Single Inheritance:

/* Double-Click To Select Code */

#include<iostream.h>
#include<conio.h>

class B
{
 private:
  int a;

 public:
  int b;
  void set_ab()
  {
   a = 5;
   b = 10;
  }

  int get_a()
  {
   return a;
  }
};

class D : public B
{
 private:
  int c;
 public:
  void mul()
  {
   c = b*get_a();
  }

  void display()
  {
   cout<<"a = "<<get_a()<<"\n";
   cout<<"b = "<<b<<"\n";
   cout<<"c = a*b = "<<c<<"\n\n";
  }
};

void main()
{
 clrscr();
 D d;
 
 d.set_ab();
 d.mul();
 d.display();
 
 d.b = 20;
 d.mul();
 d.display();

 getch();
}


Program Output:



Please Comment If You Liked The Post.


Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: