Constructor Overloading Example in C++


The code defines a class named "Area" which represents the area of a rectangle. It has private data members "length" and "breadth" and public member functions "GetLength", "Calculation" and "Display".

The "GetLength" function prompts the user to enter the length and breadth of the rectangle and sets the values of the "length" and "breadth" data members accordingly. The "Calculation" function calculates the area of the rectangle (length x breadth) and returns the result. The "Display" function takes the area as an argument and displays it.

The class has two constructors, one with no arguments which initializes the "length" and "breadth" data members to 5 and 2 respectively, and another which takes two integer arguments and sets the "length" and "breadth" data members to the values passed as arguments.

In the main function, two objects of the "Area" class are created, one using the default constructor and another using the constructor which takes two arguments. The "Calculation" and "Display" functions are called on both objects to calculate and display their respective areas.

Source Code

#include<iostream>
using namespace std;
class Area
{
  private:
    int length;
    int breadth;
  public:
    Area(): length(5), breadth(2) { }
    Area(int l, int b): length(l),breadth(b){ }
    void GetLength()
    {
       cout<<"\nEnter length of the Rectangle: ";
       cin>>length;
       cout<<"\nEnter breadth of the Rectangle: ";
       cin>>breadth;
    }
    int Calculation()
    {
      return length*breadth;
    }
    void Display(int temp)
    {
       cout<<"Area: "<<temp<<endl;
    }
};
int main()
{
    Area A1, A2(2,1);
    int temp;
    cout<<"\nDefault Area when no argument is passed."<<endl;
    temp=A1.Calculation();
    A1.Display(temp);
    cout<<"\nArea when (2,1) is passed as argument."<<endl;
    temp=A2.Calculation();
    A2.Display(temp);
    return 0;
}
To download raw file Click Here

Output

Default Area when no argument is passed.
Area: 10

Area when (2,1) is passed as argument.
Area: 2

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