Constructors in C++
In this lesson: Default, parameterized and copy constructors in C++ plus initializer lists — with examples and output. In Hindi & English.
What is a constructor?
A constructor is a special function that runs automatically the moment an object is created, to set up its data. It has the same name as the class and no return type. Without one, a new object's members would start with unpredictable values.
Default constructor
A default constructor takes no arguments and gives sensible starting values:
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int speed;
Car() { // default constructor
brand = "Unknown";
speed = 0;
}
};
int main() {
Car c; // constructor runs here
cout << c.brand << " " << c.speed << "\n";
return 0;
}Unknown 0
Parameterized constructor
Take arguments to initialise an object with specific values:
class Car {
public:
string brand;
int speed;
Car(string b, int s) { // parameterized
brand = b;
speed = s;
}
};
int main() {
Car c("Toyota", 80);
cout << c.brand << " " << c.speed; // Toyota 80
}Toyota 80
Overloading constructors
A class can have several constructors with different parameters — the compiler picks the right one:
class Box {
public:
int w, h;
Box() { w = h = 1; } // default
Box(int side) { w = h = side; } // square
Box(int a, int b) { w = a; h = b; } // rectangle
};Member initializer list
Instead of assigning inside the body, you can initialise members directly with a colon list — faster, and required for const members and references:
class Point {
public:
int x, y;
Point(int a, int b) : x(a), y(b) { } // initializer list
};Here x(a), y(b) initialises the members before the body runs.
Common mistakes
- Giving the constructor a return type — it must have none.
- Assuming the free default constructor still exists after you add another constructor.
- Naming the constructor differently from the class.
- Assigning
constmembers in the body instead of the initializer list.
Write a Student class with a parameterized constructor for name and marks, plus a default constructor. Create objects both ways and print them. Add a member initializer list version.
Summary
- A constructor runs automatically when an object is created.
- It shares the class name and has no return type.
- Default takes no arguments; parameterized takes values.
- Constructors can be overloaded with different parameter lists.
- Member initializer lists are efficient and needed for const/reference members.
Frequently Asked Questions
What is a constructor in C++?
Car() is the constructor of a class called Car.What is the difference between a default and a parameterized constructor?
Car c("Toyota", 80);.Can a class have more than one constructor in C++?
What is a member initializer list in C++?
Constructor() : member(value) { }. It is more efficient than assigning inside the body and is required for const members and references.