Constructor Function
Lesson 28Author : Afrixi
Last Updated : November, 2022
In C++, a constructor is a special member function of a class that is called when an object of the class is created. The purpose of a constructor is to initialize the object’s data members to default or specified values.
Here’s an example of how a constructor can be used in C++:
#include <iostream>
#include <string>
class Person {
public:
// default constructor
Person() {
name = "";
age = 0;
}
// parameterized constructor
Person(std::string n, int a) {
name = n;
age = a;
}
// member functions
void sayHello() {
std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl;
}
private:
std::string name;
int age;
};
int main() {
// create objects using constructors
Person p1; // calls default constructor
Person p2("Alice", 25); // calls parameterized constructor
// call member functions on the objects
p1.sayHello();
p2.sayHello();
return 0;
}
In this example, we define a Person
class with two constructors: a default constructor that initializes the object’s name
and age
data members to default values, and a parameterized constructor that takes a name and age and initializes the object’s name
and age
data members to the specified values.
In the main
function, we create two objects p1
and p2
of the Person
class, using the default and parameterized constructors respectively. We then call the sayHello
function on both objects to print a greeting with their names and ages.
Constructors are an important feature of classes in C++, as they allow us to define how objects are initialized and ensure that they are in a valid state when created.