Multiplication Example using Single Level Inheritance in C++


This program is an example of inheritance in C++ using private access specifier.

  • In this program, there are two classes A and B. Class A has two private data members a and b and a public member function mul() that returns the multiplication of a and b.
  • Class B is inherited privately from class A, which means all the public and protected members of class A will become private in class B. Class B has a public member function display() that calls the mul() function of class A to get the multiplication of a and b and displays it on the console.
  • In the main() function, an object of class B is created, and the display() function is called to show the multiplication of a and b.

Source Code

#include<iostream>
using namespace std;
class A
{
  int a = 4;
  int b = 5;
  public:
  int mul()
  {
    int c = a*b;
    return c;
  }
};
class B : private A
{
  public:
  void display()
  {
    int result = mul();
    std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
  }
};
int main()
{
  B b;
  b.display();
  return 0;
}
To download raw file Click Here

Output

Multiplication of a and b is : 20

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples