Constructor Overloading
In C++, a class can have multiple constructors, and each constructor can be used to initialize an object in different ways. This feature is known as constructor overloading. You can define constructors with different parameter lists to provide flexibility in object creation. Here's an example demonstrating multiple constructors in a class:
#include <iostream>
#include <string>
class Person {
public:
// Default constructor
Person() {
name = "Unknown";
age = 0;
}
// Parameterized constructor
Person(const std::string& n, int a) {
name = n;
age = a;
}
// Another parameterized constructor with a default value
Person(const std::string& n, int a, const std::string& occ = "Unemployed") {
name = n;
age = a;
occupation = occ;
}
// Display information about the person
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << ", Occupation: " << occupation << std::endl;
}
private:
std::string name;
int age;
std::string occupation;
};
int main() {
// Using different constructors
Person person1; // Default constructor
Person person2("John", 25); // Parameterized constructor
Person person3("Jane", 30, "Software Engineer"); // Another parameterized constructor
// Displaying information about the persons
person1.displayInfo();
person2.displayInfo();
person3.displayInfo();
return 0;
}
In this example, the `Person` class has three constructors:
1. The default constructor initializes the object with default values ("Unknown" for name and 0 for age).
2. The parameterized constructor takes a name and age to initialize the object.
3. Another parameterized constructor takes a name, age, and occupation, with the occupation having a default value of "Unemployed".
This allows you to create `Person` objects using different constructors based on your needs. Constructor overloading is a powerful feature that enhances the flexibility and usability of your classes.
Comments
Post a Comment