Constructor in C++

Level 4190 keystrokes

Defines a Rectangle class whose constructor sets private members with an initializer list, then prints the area 15.

C++ code

1class Rectangle {
// Members below are hidden from code outside the class
2private:
// Two int members declared in one line
3 int width, height;
4public:
// Constructor: the initializer list sets width and height before the (empty) body runs
5 Rectangle(int w, int h) : width(w), height(h) {}
6
// Return the area computed from the private members
7 int area() { return width * height; }
8};
9
// Call the constructor with w = 5 and h = 3
10Rectangle r(5, 3);
// Print 5 * 3 = 15
11cout << r.area() << endl;

Output

15
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • (× 6
  • )× 6
  • ;× 5
  • ,× 4
  • <× 4
  • :× 3
  • {× 3
  • }× 3
  • .× 1
  • *× 1

More C++ examples at level 4

← C++ typing practice