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:
class MyClass { ... };
: Defines a class namedMyClass
.int var1; float var2;
: Declares private member variablesvar1
andvar2
.public:
: Specifies the access level of the subsequent members as public.MyClass() { ... }
: Default constructor initializesvar1
andvar2
to default values.MyClass(int v) { ... }
: Overloaded constructor with one parameter setsvar1
to the provided valuev
andvar2
to a default value.MyClass(int v1, float v2) { ... }
: Overloaded constructor with two parameters initializesvar1
tov1
andvar2
tov2
.void display() { ... }
: Member function to display the values ofvar1
andvar2
.MyClass obj1;
: Creates an objectobj1
using the default constructor.MyClass obj2(5);
: Creates an objectobj2
using the overloaded constructor with one parameter.MyClass obj3(3, 7.5);
: Creates an objectobj3
using the overloaded constructor with two parameters.obj1.display(); obj2.display(); obj3.display();
: Calls thedisplay()
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.