November 18, 2022

Overloading in C++

Posted on November 18, 2022  •  2 minutes  • 304 words

Types Of Overloading

  1. Constructor Overloading

  2. Function Overloading

Related video link

1. Constructor Overloading

  1. All constructors have same name but

  2. different number of arguments

#include<iostream>

class Rectangle
{

public:

    // Constructor
    Rectangle()
    {
        length = 0;
        width = 0;
    }

    Rectangle(double len, double wid)
    {
        length = len;
        width = wid;
    }

    Rectangle(double side)
    {
        length = side;
        width = side;
    }

    void print()
    {
        std::cout << "length: "<< length << std::endl;
        std::cout << "width: "<< width << std::endl;
    }

    double length;
    double width;

};

int main(int argc, char const *argv[])
{

    Rectangle r1;
    r1.print();

    Rectangle r2(100,200);
    r2.print();

    Rectangle s(50);
    s.print();

    return 0;
}

2. Function Overloading

  1. All overloading functions have same name,
  2. All overloading functions have same return-type,
  3. but different number of arguments
#include<iostream>

class Rectangle
{
public:

    // Constructor
    Rectangle()
    {
        length = 0;
        width = 0;
    }

    Rectangle(double len, double wid)
    {
        length = len;
        width = wid;
    }

    Rectangle(double side)
    {
        length = side;
        width = side;
    }

    void print()
    {
        std::cout << "length: "<< length << std::endl;
        std::cout << "width: "<< width << std::endl;
    }

    // overloaded function with zero arguments
    double getArea()
    {
        return length * width;
    }

    // overloaded function with one arguments
    double getArea(double side)
    {
        return side * side;
    }

    // overloaded function with two arguments
    double getArea(double l, double w)
    {
        return l * w;
    }

    double length, width;
};


int main(int argc, char const *argv[])
{
    Rectangle r1;
    r1.print();
    std::cout << "Area : " << r1.getArea() << std::endl;

    Rectangle r2(100,200);
    r2.print();
    std::cout << "Area : " << r2.getArea() << std::endl;

    Rectangle s(50);
    s.print();
    std::cout << "Area : " << s.getArea() << std::endl;

    Rectangle r3;
    std::cout << "Area : " << r3.getArea() << std::endl;
    std::cout << "Area : " << r3.getArea(10,10) << std::endl;
    std::cout << "Area : " << r3.getArea(20) << std::endl;
    
    return 0;
}
Follow me

I work on everything coding and share developer memes