C++
Summary - Constructor
Combine overloading and initializer list to write a Product class.
Summary - Constructor
In this section you learned constructors and destructors. A constructor has the same name as the class, no return type and is called automatically when an object is created. A parameterized constructor takes values from outside; the member initializer list initializes members directly after a colon.
You can define more than one constructor in a class (overloading); the compiler selects by parameters. A destructor starts with a tilde, is called automatically when an object leaves scope and cleans up resources. Now we will bring these together in a task.
Exercise Add a constructor and destructor to the Counter class
Define a Counter class. Under public: add int count;, the constructor Counter() { count = 0; std::cout << "Built"; } and the destructor ~Counter() { std::cout << "Destroyed"; }. In main create a Counter c; instance.
Show example solution
#include <iostream>
class Counter {
public:
int count;
Counter() {
count = 0;
std::cout << "Built";
}
~Counter() {
std::cout << "Destroyed";
}
};
int main() {
Counter c;
return 0;
}
Exercise Add a parameterized constructor to Counter
Add the parameterized constructor Counter(int start) : count(start) { std::cout << "Built"; } to the Counter class above with an initializer list (keep the default constructor too). In main create Counter c(10); and print its value with std::cout << c.count;.
Show example solution
#include <iostream>
class Counter {
public:
int count;
Counter() {
count = 0;
std::cout << "Built";
}
Counter(int start) : count(start) {
std::cout << "Built";
}
~Counter() {
std::cout << "Destroyed";
}
};
int main() {
Counter c(10);
std::cout << c.count;
return 0;
}
What's next?
You learned the object lifecycle with constructors, initializer lists and destructors. Objects are powerful on their own, but C++ truly shines with inheritance.
In the next section you will learn to derive a new class from an existing one, achieve runtime polymorphism with virtual and override, and close inheritance with final. Inheritance reduces code duplication and lets you build class hierarchies.
Test yourself
-
What does the colon do in Player(std::string n, int l) : name(n), level(l) { }?
Player(std::string n, int l) : name(n), level(l) { }
- Marks a class hierarchy
- Starts the member initializer list
- Separates two statements
- Marks a label
Show answer
Starts the member initializer list — The colon starts the initializer list, before the body.
-
Write the destructor mark
class Logger { public: ____Logger() { } };
Show answer
class Logger { public: ~Logger() { } };
Next lesson: Inheritance basics