Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 3 - OOP

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Unit 3

Inheritance is the capability of one class to acquire properties and characteristics from another
class. The class whose properties are inherited by other class is called
the Parent or Base or Super class. And, the class which inherits properties of other class is
called Child or Derived or Sub 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

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;

}
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 Public Mode Private Mode Protected Mode


class

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.

// C++ program to explain


// Single inheritance
#include <iostream>
using namespace std;
 // base class
class Vehicle {
  public:
    Vehicle()
    {
      cout << "This is a Vehicle" << endl;
    }
};
 class Car: public Vehicle{
 };
int main()
{  
    // creating object of sub class will
    // invoke the constructor of base classes
    Car obj;
    return 0;
}

Multiple Inheritance in C++


In this type of inheritance a single child class may inherit from two or more than two base classes.
// C++ program to explain
// multiple inheritance
#include <iostream>
using namespace std;
 
// first base class
class Vehicle {
  public:
    Vehicle()
    {
      cout << "This is a Vehicle" << endl;
    }
};
 
// second base class
class FourWheeler {
  public:
    FourWheeler()
    {
      cout << "This is a 4 wheeler Vehicle" << endl;
    }
};
 
// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {
 
}; 
// main function
int main()
{  
    // creating object of sub class will
    // invoke the constructor of base classes
    Car obj;
    return 0;
}

Output
This is a Vehicle
This is a 4 wheeler Vehicle
Hierarchical Inheritance in C++
In this type of inheritance, multiple derived classes inherits from a single base class.

// C++ program to implement


// Hierarchical Inheritance
#include <iostream>
using namespace std;
 
// base class
class Vehicle
{
  public:
    Vehicle()
    {
      cout << "This is a Vehicle" << endl;
    }
};
  
// first sub class
class Car: public Vehicle
{
 
};
 
// second sub class
class Bus: public Vehicle
{
     
};
 
// main function
int main()
{  
    // creating object of sub class will
    // invoke the constructor of base class
    Car obj1;
    Bus obj2;
    return 0;
}

Output
This is a Vehicle
This is a Vehicle

Multilevel Inheritance in C++


In this type of inheritance the derived class inherits from a class, which in turn inherits from some
other class. The Super class for one, is sub class for the other.

#include <iostream>
using namespace std;

class A {
public:
void display{
cout<<"Base class content.";
}
};

class B : public A {};

class C : public B {};

int main() {
C obj;
obj.display();
return 0;
}
Output
Base class content.
Hybrid (Virtual) Inheritance in C++
Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

// C++ program to demonstrate hierarchical inheritance

#include <iostream>
using namespace std;

// base class
class Animal {
public:
void info() {
cout << "I am an animal." << endl;
}
};

// derived class 1
class Dog : public Animal {
public:
void bark() {
cout << "I am a Dog. Woof woof." << endl;
}
};

// derived class 2
class Cat : public Animal {
public:
void meow() {
cout << "I am a Cat. Meow." << endl;
}
};

int main() {
// Create object of Dog class
Dog dog1;
cout << "Dog Class:" << endl;
dog1.info(); // Parent Class function
dog1.bark();

// Create object of Cat class


Cat cat1;
cout << "\nCat Class:" << endl;
cat1.info(); // Parent Class function
cat1.meow();

return 0;
}
Output
Dog Class:
I am an animal.
I am a Dog. Woof woof.

Cat Class:
I am an animal.
I am a Cat. Meow.

An Introduction to Virtual Base Class in C++


Ever wondered what virtual base classes are? You can use them in virtual
inheritance in a technique of checking multiple “instances” of a specified class
looking in an inheritance hierarchy through multiple inheritances. When you use
multiple inheritances, a virtual base class in C++ is used to avoid multiple "instances"
of a given class from occurring in an inheritance hierarchy. 
Now, in this article, you will explore the virtual base class in C++ as a whole.
Consider the case where there is just one class A. Two other grades, B and C,
descend from this class A.
The data members/functions of class A are inherited twice to class D, as seen in the
diagram. The first will take you through class B, and the second will take you through
class C. When an object of class D accesses any data or function member of class
A, it's unclear which data or function member would be named. One was inherited
via B, and it inherited the other via C. This throws the compiler into a loop and
causes an error to appear.
Example:
#include <iostream>
using namespace std;
class A {
   public:
   int a;
   A(){
      a = 10;
   }
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main(){
   //creating class D object
   D object;
   cout << "a = " << object.a << endl;
   return 0;
}
Output

Ever wondered what virtual base classes are? You can use them in virtual
inheritance in a technique of checking multiple “instances” of a specified class
looking in an inheritance hierarchy through multiple inheritances. When you use
multiple inheritances, a virtual base class in C++ is used to avoid multiple "instances"
of a given class from occurring in an inheritance hierarchy. 
Now, in this article, you will explore the virtual base class in C++ as a whole.
Consider the case where there is just one class A. Two other grades, B and C,
descend from this class A.

The data members/functions of class A are inherited twice to class D, as seen in the
diagram. The first will take you through class B, and the second will take you through
class C. When an object of class D accesses any data or function member of class
A, it's unclear which data or function member would be named. One was inherited
via B, and it inherited the other via C. This throws the compiler into a loop and
causes an error to appear.
Example:
#include <iostream>
using namespace std;
class A {
   public:
   int a;
   A(){
      a = 10;
   }
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main(){
   //creating class D object
   D object;
   cout << "a = " << object.a << endl;
   return 0;
}
Output

The Syntax for Virtual Base Classes


Instead of writing entirely new data members and member functions while
constructing a class, the programmer may specify that the new virtual base class in
C++ can inherit the members of an existing class. The original class is known as the
base class, while the current class is known as the derived class.
It may descend a class from various base classes or interfaces, allowing it to inherit
data and functions from multiple sources.
Syntax 1:
class B : virtual public A 
{
};
Syntax 2:
class C : public virtual A
{
};

#include<iostream>
using namespace std;
class B {
   public: int b;
};

class D1 : virtual public B {


   public: int d1;
};

class D2 : virtual public B {


   public: int d2;
};
class D3 : public D1, public D2 {
   public: int d3;
};

int main() {
   D3 obj;

   obj.b = 40; // statement 3


   obj.b = 30; // statement 4

   obj.d1 = 60;
   obj.d2 = 70;
   obj.d3 = 80;

   cout<< "\n B : "<< obj.b;


   cout<< "\n D1 : "<< obj.d1;
   cout<< "\n D2 : "<< obj.d2;
   cout<< "\n D3 : "<< obj.d3;
}
Output
B : 30
D1 : 60
D2 : 70
D3 : 80
Now, D3 have only one copy of B and statement 4 will overwrite the value of b, given
in statement 3.

Abstract Class
By definition, an abstract class in C++ is a class that has at
least one pure virtual function (i.e., a function that has no definition). The
classes inheriting the abstract class must provide a definition for the pure
virtual function; otherwise, the subclass would become an abstract class
itself.

Abstract classes are essential to providing an abstraction to the code to


make it reusable and extendable. For example, a Vehicle parent class
with Truck and Motorbike inheriting from it is an abstraction that easily
allows more vehicles to be added. However, even though all vehicles have
wheels, not all vehicles have the same number of wheels – this is where a
pure virtual function is needed.

Consider an example of a Shape base class with sub-classes


(Triangle and Rectangle) that inherit the Shape class.
Now, suppose we need a function to return the area of a shape. The
function will be declared in the Shape class; however, it cannot be defined
there as the formula for the area is different for each shape. A non-specific
shape does not have an area, but rectangles and triangles do. Therefore, the
pure virtual function for calculating area will be implemented differently by
each sub-class.
The following code snippet implements the abstract Shape class along with its sub-classes: #include
<iostream>

using namespace std;

class Shape {
   public:
      virtual int Area() = 0; // Pure virtual function is declared as follows.
      // Function to set width.
      void setWidth(int w) {
         width = w;
   }
      // Function to set height.
      void setHeight(int h) {
         height = h;
   }
  
   protected:
      int width;
      int height;
};

// A rectangle is a shape; it inherits shape.


class Rectangle: public Shape {
   public:
      // The implementation for Area is specific to a rectangle.
      int Area() {
         return (width * height);
   }
};
// A triangle is a shape too; it inherits shape.
class Triangle: public Shape {
   public:
      // Triangle uses the same Area function but implements it to
      // return the area of a triangle.
      int Area() {
         return (width * height)/2;
   }
};

int main() {
  Rectangle R;
  Triangle T;

  R.setWidth(5);
  R.setHeight(10);

  T.setWidth(20);
  T.setHeight(8);

  cout << "The area of the rectangle is: " << R.Area() << endl;
  cout << "The area of the triangle is: " << T.Area() << endl;
}

You might also like