C++ Constructors
In this page:
What is a Constructor?
A constructor is a special member function that runs automatically every time an object is created. It shares the exact same name as the class, has no return type at all (not even void), and is the natural place to set up an object's initial state.
Example: What is a Constructor?
#include <iostream>
class Car {
public:
Car() { std::cout << "Car created" << std::endl; }
};
int main() {
Car myCar;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Default Constructor
A default constructor takes no arguments. If you don't define any constructor yourself, C++ silently generates a blank default one for you — though as soon as you write any constructor of your own, that automatic one disappears and you must provide it explicitly if you still need it.
Example: Default Constructor
#include <iostream>
class Box {
public:
int size = 10; // no constructor written: compiler generates a blank default one
};
int main() {
Box b;
std::cout << b.size << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Parameterized Constructor
A parameterized constructor accepts arguments, letting you initialize an object's member variables with specific values right at the moment of creation instead of setting them one by one afterward through separate assignment statements.
Example: Parameterized Constructor
#include <iostream>
class Point {
public:
int x, y;
Point(int px, int py) {
x = px;
y = py;
}
};
int main() {
Point p(3, 4);
std::cout << p.x << "," << p.y << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Constructor Initializer List
A constructor initializer list is the preferred way to initialize member variables, since it initializes them directly before the constructor body even starts running — this is more efficient than assigning values inside the body, and it's required for const or reference members.
Example: Constructor Initializer List
#include <iostream>
class Point {
public:
int x, y;
Point(int px, int py) : x(px), y(py) {}
};
int main() {
Point p(3, 4);
std::cout << p.x << "," << p.y << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Constructor Overloading
You can define multiple constructors in the same class with different parameter lists, a technique called constructor overloading. C++ automatically selects the matching constructor based on the number and types of arguments you supply when creating the object.
Example: Constructor Overloading
#include <iostream>
class Point {
public:
int x, y;
Point() : x(0), y(0) {}
Point(int px, int py) : x(px), y(py) {}
};
int main() {
Point p1;
Point p2(3, 4);
std::cout << p1.x << " " << p2.x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: