Constructors
C++ Constructors
Definition: A constructor is a special member function of a class that is executed automatically whenever a new object of that class is created. Its primary purpose is to initialize the object's attributes and set up any necessary resources before the object is used.
Why: Constructors are a core part of the C++ syllabus because they ensure that every object starts its life in a valid state. Without constructors, you would have to manually assign values to every variable each time you create an object, which is repetitive and prone to errors.
Rules for Creating Constructors
Constructors follow three strict rules that distinguish them from regular class methods:
- Same Name: The constructor must have the exact same name as the class.
- No Return Type: It does not have a return type (not even
void). - Automatic Trigger: It cannot be called like a normal function; the system triggers it the moment you declare an object.
Example: Automatic Initialization
In the following code, the message "Car created" is printed to the console the moment the c1 object is declared in main(), even though we never explicitly call a function:
#include <iostream> using namespace std; class Car { public: // Constructor: Same name as class, no return type Car() { cout << "Car created" << endl; } }; int main() { // Object creation triggers the constructor automatically Car c1; return 0; }
Types of Constructors
| Type | Description |
|---|---|
| Default Constructor | Takes no parameters. If you don't define any constructor, C++ provides a hidden empty one for you. |
| Parameterized Constructor | Accepts arguments to initialize attributes with specific values during creation (e.g., Car c1("Tesla");). |
| Copy Constructor | Used to create a new object as a copy of an existing object. |
Key Notes
- Public Access: Constructors are almost always placed in the
publicsection. If a constructor is private, you won't be able to create objects of that class from outside the class. - Overloading: Just like regular functions, constructors can be overloaded. You can have one class with multiple constructors, as long as they have different parameter lists.
- Initializers: Professional C++ developers often use "Member Initializer Lists" for better performance, which looks like this:
Car() : brand("Unknown") {}. - Destructors: Every class can also have a Destructor (e.g.,
~Car()), which runs automatically when an object is destroyed or goes out of scope, used for cleaning up memory.
🏋️ Test Yourself With Exercises
Take our quiz on Constructors to test your knowledge.
Browse Quizzes »