CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

main.cpp
#include <iostream>

// Define the Timer class here

int main() {
    // Create a Timer instance and print seconds
    return 0;
}

Sample solution

main.cpp
#include <iostream>

class Timer {
public:
    Timer() {
        seconds = 0;
    }
    int seconds;
};

int main() {
    Timer t;
    std::cout << t.seconds;
    return 0;
}

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is no return type written in a constructor header?

main.cpp
Timer() { seconds = 0; }
  • Because it is treated as void
  • Because a constructor returns no value Correct answer
  • Because the compiler adds one
  • Because int is assumed

Explanation: A constructor returns no value, so it has no return type.

2 Complete the constructor name

Question
class Timer { public: ____() { seconds = 0; } int seconds; };
Answer
class Timer { public: Timer() { seconds = 0; } int seconds; };

Explanation: The constructor has the same name as the class: Timer().

3 Match each trait to its meaning

Term Meaning
Same name as class Constructor name
No return type Constructor signature
When object declared Automatic call moment
In public section Accessibility

All lessons in Intermediate