0% found this document useful (0 votes)
167 views

Purpose of Inheritance in C++

The document discusses inheritance in C++. It defines inheritance as a capability of a class to derive properties and characteristics from another class, called the base/super class. The class inheriting is called a derived/sub class. Inheritance allows code reuse and method overriding for runtime polymorphism. The document provides examples of different types of inheritance in C++ like single, multiple, hierarchical and multilevel inheritance. It also discusses access specifiers and their effect on inheritance, and need for virtual destructors and virtual base classes.

Uploaded by

harini
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

Purpose of Inheritance in C++

The document discusses inheritance in C++. It defines inheritance as a capability of a class to derive properties and characteristics from another class, called the base/super class. The class inheriting is called a derived/sub class. Inheritance allows code reuse and method overriding for runtime polymorphism. The document provides examples of different types of inheritance in C++ like single, multiple, hierarchical and multilevel inheritance. It also discusses access specifiers and their effect on inheritance, and need for virtual destructors and virtual base classes.

Uploaded by

harini
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Inheritance in C++

The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or
Super class.

Inheritance makes the code reusable. When we inherit an existing class, all its methods and
fields become available in the new class, hence code is reused.

NOTE: All members of a class except Private, are inherited

Purpose of Inheritance in C++

1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword

Basic Syntax of Inheritance


class Subclass_name : access_mode Superclass_name

While defining a subclass like this, the super class must be already defined or atleast declared
before the subclass declaration.

Access Mode is used to specify, the mode in which the properties of superclass will be
inherited into subclass, public, privtate or protected.

Example of Inheritance

Whenever we want to use something from an existing class in a new class, we can use the
concept on Inheritace. Here is a simple example,
class Animal
{
public:
int legs = 4;
};

// Dog class inheriting Animal class


class Dog : public Animal
{
public:
int tail = 1;
};

int main()
{
Dog d;
cout << d.legs;
cout << d.tail;
}
Output:

41

Access Modifiers and Inheritance: Visibility of Class Members

Depending on Access modifier used while inheritance, the availability of class members of
Super class in the sub class changes. It can either be private, protected or public.

1) Public Inheritance

This is the most used inheritance mode. In this the protected member of super class becomes
protected members of sub class and public becomes public.

class Subclass : public Superclass


2) Private Inheritance

In private mode, the protected and public members of super class become private members of
derived class.

class Subclass : Superclass // By default its private inheritance

3) Protected Inheritance

In protected mode, the public and protected members of Super class becomes protected
members of Sub class.

class subclass : protected Superclass

Table showing all the Visibility Modes


Derived Class Derived Class Derived Class

Base class Public Mode Private Mode Protected Mode

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected

Types of Inheritance in C++


In C++, we have 5 different types of Inheritance. Namely,

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

Single Inheritance in C++

In this type of inheritance one derived class inherits from only one base class. It is the most
simplest form of Inheritance.
Multiple Inheritance in C++

In this type of inheritance a single derived class may inherit from two or more than two base
classes.

Hierarchical Inheritance in C++

In this type of inheritance, multiple derived classes inherits from a single base class.
Multilevel Inheritance in C++
In this type of inheritance a class is derived from a class which is also a derived class of another class.

Hybrid (Virtual) Inheritance in C++

Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.


/ C++ Implementation to show that a derived class
// doesn’t inherit access to private data members. 
// However, it does inherit a full parent object
class A 
{
public:
    int x;
protected:
    int y;
private:
    int z;
};
  
class B : public A
{
    // x is public
    // y is protected
    // z is not accessible from B
};
  
class C : protected A
{
    // x is protected
    // y is protected
    // z is not accessible from C
};
  
class D : private A    // 'private' is default for classes
{
    // x is private
    // y is private
    // z is not accessible from D
};
Virtual Destructor. Deleting a derived class object using a pointer to a base class that has a non-
virtual destructor results in undefined behavior. ... To correct this situation, the base class should be
defined with a virtual destructor.

For example, following program results in undefined behavior.

// CPP program without virtual destructor 


// causing undefined behavior
#include<iostream>
  
using namespace std;
  
class base {
  public:
    base()     
    { cout<<"Constructing base \n"; }
    ~base()
    { cout<<"Destructing base \n"; }     
};
  
class derived: public base {
  public:
    derived()     
    { cout<<"Constructing derived \n"; }
    ~derived()
    { cout<<"Destructing derived \n"; }
};
  
int main(void)
{
  derived *d = new derived();  
  base *b = d;
  delete b;
  getchar();
  return 0;
}

Although the output of following program may be different on different compilers, when
compiled using Dev-CPP, it prints following:

Constructing base
Constructing derived
Destructing base

Virtual destructor in base class ensures that the destructor of derived class will be called when using
base pointer to the object.For example,

// A program with virtual destructor


#include<iostream>
  
using namespace std;
  
class base {
  public:
    base()     
    { cout<<"Constructing base \n"; }
    virtual ~base()
    { cout<<"Destructing base \n"; }     
};
  
class derived: public base {
  public:
    derived()     
    { cout<<"Constructing derived \n"; }
    ~derived()
    { cout<<"Destructing derived \n"; }
};
  
int main(void)
{
  derived *d = new derived();  
  base *b = d;
  delete b;
  getchar();
  return 0;
}

Output:
Constructing base
Constructing derived
Destructing derived
Destructing base
C++ Virtual Base Class

Virtual base class is used in situation where a derived have multiple copies of base class.
Consider the following figure:

Need for Virtual Base Classes:


Consider the situation where we have one class A .This class is A is inherited by two other classes B
and C. Both these class are inherited into another in a new class D as shown in figure below.

From the fig it is clear that class d will have 2 copies of class a-one from b and other from c which
leads to ambiguity.because when we try to call any member of class a using class d obj the compiler

Shows error becoz it cant differentiate bet the 2 copies of class a in d.

Example: To show the need of Virtual Base Class in C++

#include <iostream>
using namespace std;
  
class A {
public:
    void show()
    {
        cout << "Hello form A \n";
    }
};
  
class B : public A {
};
  
class C : public A {
};
  
class D : public B, public C {
};
  
int main()
{
    D object;
    object.show();
}

Compile Errors:

prog.cpp: In function 'int main()':


prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();

the above problem can be overcome by making base classes B,C as virtual.

STATIC BINDING:

Static binding occurs at compile time.so this is also called as early binding.

In static binding linking of func call with fun def happens at compile time.

Static bin occurs when all the info needed for the exec of func is available at compile time.

Since all the info is available before runtime itself ,therefore static bin results in faster exec of code

It can be achieved through func overloading or op overloading.

Ex:

/* overloading binary + operator - Example

output:

The Complx No is :2+3i

The Complx No is :5+2i

The Complx No is :7+5i

*/
#include<iostream>

using namespace std;

class Complex

int real,img;

// write code here

public:

Complex()

real=0;

img=0;

Complex(int real,int img)

this->real=real;

this->img=img;

void display()

cout<<"The Complx No is :"<<real<<"+"<<img<<"i"<<endl;

Complex operator+(Complex c){

Complex temp;

temp.real=real+c.real;

temp.img=img+c.img;

return temp;

}
};

int main()

Complex c1(2,3);

c1.display();

Complex c2(5,2);

c2.display();

Complex c3;

c3=c1+c2;

c3.display();

cout<<"\n";

return 0;

DYNAMIC BINDING:

Dynamic binding occurs at run time.so this is also called as late binding.

In dynamic binding linking of func call with fun def happens at run time.

Dynamic bin occurs when all the info needed for the exec of func cannot be determined at compile
time.

Since all the info is available at runtime itself ,therefore dynamic bin results in slower exec of code

It can be achieved through virtual funcns.

#include <iostream>
using namespace std;

class Animals

public:

virtual void sound()

cout << "This is parent class" << endl;

};

class Dogs : public Animals

public:

void sound()

cout << "Dogs bark" << endl;

};

int main()

Animals *a;

Dogs d;

a= &d;

a -> sound();

return 0;

Op:

Dogs bark
Virtual Function is a member function of the base class which is overridden in the derived class. The
compiler performs late binding on this function.

To make a function virtual, we write the keyword virtual before the function definition.

It follows the concept of one interface multiple methods.


#include <iostream>
using namespace std;
class base
{
public:
virtual void vfunc()
{
cout << "This is base's vfunc().\n";
}};
class derived1 : public base
{
public:void vfunc()
{
cout << "This is derived1's vfunc().\n";
}
};
class derived2 : public base
{
public:void vfunc()
{
cout << "This is derived2's vfunc().\n";
}};
int main()
{
base *p, b;
derived1 d1;
derived2 d2;
// point to base
p = &b;
p->vfunc(); // access base's vfunc()
// point to derived1
p = &d1;
p->vfunc(); // access derived1's vfunc()
// point to derived2
p = &d2;
p->vfunc(); // access derived2's vfunc()
return 0;
}

This program displays the following:


This is base's vfunc().
This is derived1's vfunc().
This is derived2's vfunc()

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t
have implementation, we only declare it. A pure virtual function is declared by assigning 0 in
declaration.

We must implement all pure virtual functions in derived class.otherwise the compiler shows
error.

Pure virtual function is also known as abstract function.

A class with at least one pure virtual function or abstract function is called abstract class. We
can't create an object of abstract class

Member functions of abstract class will be invoked by derived class object.

See the following example.

// An abstract class

class Test

{   

    // Data members of class

public:

    // Pure Virtual Function

    virtual void show() = 0;

    

   /* Other members */

};

#include<iostream>
using namespace std;
  
class Base
{
public:
    virtual void show() = 0;
};
  
class Derived: public Base
{
public:
    void show() { cout << "In Derived \n"; }
};
  e
int main(void)
{
    Base *bp = new Derived();
    bp->show();
    return 0;
}

Output:

In Derived

Example of C++ Abstract class


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

class BaseClass //Abstract class


{

public:
virtual void Display1()=0; //Pure virtual function or
abstract function
virtual void Display2()=0; //Pure virtual function or
abstract function

void Display3()
{
cout<<"\n\tThis is Display3() method of Base Class";
}

};

class DerivedClass : public BaseClass


{

public:
void Display1()
{
cout<<"\n\tThis is Display1() method of Derived
Class";
}

void Display2()
{
cout<<"\n\tThis is Display2() method of Derived
Class";
}
};

void main()
{

DerivedClass D;

D.Display1(); // This will invoke Display1()


method of Derived Class
D.Display2(); // This will invoke Display2()
method of Derived Class
D.Display3(); // This will invoke Display3()
method of Base Class

Output :

This is Display1() method of Derived Class


This is Display2() method of Derived Class
This is Display3() method of Base Class

You might also like