Classes and OOP · Lesson 15 of 21
Constructors and destructors
Initializer lists, when destructors run, and the rules of zero and three.
A constructor is a function named after the class that runs when an object is created and sets it up. A destructor (~Name) runs when the object dies. The best way to give members their values is the initializer list after :.
#include <iostream>
#include <string>
class Student {
public:
Student(std::string name, int level = 1)
: name_(std::move(name)), level_(level) {
std::cout << "hello " << name_ << "\n";
}
~Student() { std::cout << "bye " << name_ << "\n"; }
std::string describe() const { return name_ + " L" + std::to_string(level_); }
private:
std::string name_;
int level_;
};
int main() {
Student a("Laila", 3);
{
Student b("Omar");
std::cout << b.describe() << "\n";
} // b dies here
std::cout << a.describe() << "\n";
return 0;
} // a dies here- ▶Student a("Laila", 3);
- 2{
- 3 Student b("Omar");
- 4 std::cout << b.describe();
- 5}
- 6std::cout << a.describe();
- 7return 0;
Variables
| a | Laila L3 |
Output
Follow when each object is born and dies.
The rule of zero and the rule of three
If a class only uses self-managing members (std::string, std::vector, smart pointers), don't write a destructor, copy constructor or copy assignment: the compiler's versions are correct. That's the rule of zero.
If a class manages a resource by hand (a pointer from new), the default copy copies just the pointer, leaving two objects that free the same memory. Then you must write all three (destructor, copy constructor, copy assignment), or more simply switch to unique_ptr or vector.
What's the output?
#include <iostream>
struct A {
char c;
A(char x) : c(x) { std::cout << c; }
~A() { std::cout << (char)(c - 32); }
};
int main() {
A x('a');
A y('b');
std::cout << "-";
}What will this code print?
Exercise
Make a Box class whose constructor takes an int and prints + and the number, and whose destructor prints - and the number. In main create Box 1, then Box 2 inside a block. The output must be +1 +2 -2 -1 on one line.
Expected output: +1 +2 -2 -1
#include <iostream>
class Box {
};
int main() {
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.