C++
Constructor
Learn to define a class constructor.
Constructor
A constructor is a special member function called automatically when an object is created. It has the same name as the class and no return type. Its purpose is to give initial values to member variables.
Example: class Timer { public: Timer() { seconds = 0; } int seconds; };. Here Timer() is the constructor. When you write Timer t;, this function is called automatically and seconds is set to zero. You no longer need a manual assignment. A constructor with no parameters is called the default constructor.
Automatic call
A constructor is not called from main; it runs automatically the moment an object is declared. The line Timer t; both creates an object and runs the Timer() constructor. You do not need to add parentheses.
If you declare several objects, the constructor is called for each one: Timer a, b; runs it twice. The constructor must be in the public section of the class; otherwise Timer t; gives a compile error. Members are allocated in memory before the constructor runs; the constructor fills them with meaningful values.
Exercise Add a default constructor to the Timer class
Define a Timer class. Under public: add the constructor Timer() { seconds = 0; } and the int seconds; member variable. In main create an instance and print seconds with std::cout.
Show example solution
#include <iostream>
class Timer {
public:
Timer() {
seconds = 0;
}
int seconds;
};
int main() {
Timer t;
std::cout << t.seconds;
return 0;
}
Test yourself
-
Why is no return type written in a constructor header?
Timer() { seconds = 0; }
- Because it is treated as void
- Because a constructor returns no value
- Because the compiler adds one
- Because int is assumed
Show answer
Because a constructor returns no value — A constructor returns no value, so it has no return type.
-
Complete the constructor name
class Timer { public: ____() { seconds = 0; } int seconds; };
Show answer
class Timer { public: Timer() { seconds = 0; } int seconds; };
-
Match each trait to its meaning
- Same name as class
- Constructor name
- No return type
- Constructor signature
- When object declared
- Automatic call moment
- In public section
- Accessibility
Next lesson: Parameterized constructor