← Back to C++ Course | Chapter 8: OOP Core | Lesson 5 of 14

C++ Constructors

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?

cpp
#include <iostream>

class Car {
public:
	Car() { std::cout << "Car created" << std::endl; }
};

int main() {
	Car myCar;
	return 0;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.