This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, February 17, 2023

write a program to demonstrate constructor overloading.

 Here's an example program that demonstrates constructor overloading in C++:

#include <iostream>
using namespace std;

class Rectangle {
   private:
    int length, width;

   public:
    // Default constructor
    Rectangle() {
        length = 0;
        width = 0;
    }

    // Parameterized constructor with one argument
    Rectangle(int l) {
        length = l;
        width = l;
    }

    // Parameterized constructor with two arguments
    Rectangle(int l, int w) {
        length = l;
        width = w;
    }

    // Method to calculate and return the area of the rectangle
    int area() {
        return length * width;
    }
};

int main() {
    // Create objects of Rectangle class with different constructors
    Rectangle rect1;
    Rectangle rect2(5);
    Rectangle rect3(4, 6);

    // Print the area of each rectangle
    cout << "Area of rect1: " << rect1.area() << endl;
    cout << "Area of rect2: " << rect2.area() << endl;
    cout << "Area of rect3: " << rect3.area() << endl;

    return 0;
}

In this program, we define a 'Rectangle' class that has three constructors: a default constructor that sets both 'length' and 'width' to 0, a parameterized constructor with one argument that sets both 'length' and 'width' to the same value, and a parameterized constructor with two arguments that sets 'length' and 'width' separately.

We then create three objects of the "Rectangle" class using each of the three constructors, and calculate and print the area of each rectangle using the 'area()' method.

This program demonstrates how constructor overloading can provide flexibility and convenience when creating objects of a class.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget