how to make an overloaded constructor in c++

Certainly! Here is an example of how you can create overloaded constructors in C++:

#include <iostream>
using namespace std;

class MyClass {
    int var1;
    float var2;

public:
    // Default constructor
    MyClass() {
        var1 = 0;
        var2 = 0.0;
    }

    // Overloaded constructor with one parameter
    MyClass(int v) {
        var1 = v;
        var2 = 0.0;
    }

    // Overloaded constructor with two parameters
    MyClass(int v1, float v2) {
        var1 = v1;
        var2 = v2;
    }

    // Function to display values
    void display() {
        cout << "var1: " << var1 << ", var2: " << var2 << endl;
    }
};

int main() {
    MyClass obj1; // Default constructor called
    MyClass obj2(5); // Overloaded constructor with one parameter called
    MyClass obj3(3, 7.5); // Overloaded constructor with two parameters called

    obj1.display();
    obj2.display();
    obj3.display();

    return 0;
}

Explanation:

  1. class MyClass { ... };: Defines a class named MyClass.

  2. int var1; float var2;: Declares private member variables var1 and var2.

  3. public:: Specifies the access level of the subsequent members as public.

  4. MyClass() { ... }: Default constructor initializes var1 and var2 to default values.

  5. MyClass(int v) { ... }: Overloaded constructor with one parameter sets var1 to the provided value v and var2 to a default value.

  6. MyClass(int v1, float v2) { ... }: Overloaded constructor with two parameters initializes var1 to v1 and var2 to v2.

  7. void display() { ... }: Member function to display the values of var1 and var2.

  8. MyClass obj1;: Creates an object obj1 using the default constructor.

  9. MyClass obj2(5);: Creates an object obj2 using the overloaded constructor with one parameter.

  10. MyClass obj3(3, 7.5);: Creates an object obj3 using the overloaded constructor with two parameters.

  11. obj1.display(); obj2.display(); obj3.display();: Calls the display() function for each object to print their respective member variables.

This code demonstrates the concept of overloaded constructors in C++, allowing the creation of objects with different initialization values based on the constructor used.