Constructors are special member functions in C++ that are automatically called when an object of a class is created. They are used to initialize the data members of an object and perform any necessary setup.
Syntax
C++
class MyClass {
public:
MyClass() {
// Constructor body
}
};
Types of Constructors
Default Constructor: A constructor with no parameters. It is automatically generated by the compiler if no other constructors are defined.
Parameterized Constructor: A constructor that takes parameters to initialize the data members of the object.
Copy Constructor: A constructor that takes an object of the same class as a parameter and creates a copy of that object.
Example: Default Constructor
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person() {
cout << "Default constructor called" << endl;
}
};
int main() {
Person p1; // Default constructor is called
return 0;
}
Output:
Default constructor called
Example: Parameterized Constructor
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person(string name, int age) {
this->name = name;
this->age = age;
}
};
int main() {
Person p2("Alice", 25);
cout << "Name: " << p2.name << endl;
cout << "Age: " << p2.age << endl;
return 0;
}
Output:
Name: Alice
Age: 25
Example: Copy Constructor
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person(string name, int age) {
this->name = name;
this->age = age;
}
Person(const Person& other) {
name = other.name;
age = other.age;
}
};
int main() {
Person p3("Bob", 30);
Person p4 = p3; // Copy constructor is called
cout << "p4.name: " << p4.name << endl;
cout << "p4.age: " << p4.age << endl;
return 0;
}
Output:
p4.name: Bob
p4.age: 30
Key Points:
Constructors are used to initialize objects.
Default constructors are automatically generated if not defined.
Parameterized constructors take parameters to initialize data members.
Copy constructors are used to create copies of objects.
The this pointer can be used to refer to the current object within a member function.
By understanding constructors, you can effectively initialize objects and control their creation in C++.
Comments