← C++ from Scratch
Lesson 38 of 62 · 10 XP
Constructors
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A constructor is a special method with the class's name and no result type. It's called when an object is created:
class Hero {
public:
Hero(std::string n, int h) : name(n), hp(h) {} // the initialiser list after :
Hero() : Hero("Nameless", 100) {} // the default constructor, delegates to the first one
~Hero() { std::cout << name << " has left\n"; } // the destructor: called on destruction
private:
std::string name;
int hp;
};
Hero a("Kai", 120);
Hero b; // "Nameless", 100
A constructor guarantees that an object is correct right away: you can't forget to set the name. A destructor frees resources — that's RAII (module 3): a file gets closed, memory gets returned.
Task. A class Rect with a constructor Rect(int w, int h); if a side is negative, the constructor makes it 0.
The methods area() and perimeter(). Read w h and print the area and the perimeter separated by a space.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.