Struct basics in C++

Level 4154 keystrokes

Defines a Point struct with a print method, creates two points with aggregate initialization and prints them.

C++ code

// A struct is like a class, but its members are public by default
1struct Point {
// Two public int coordinates
2 int x, y;
3
// Method that prints the point in the form (x, y)
4 void print() {
5 cout << "(" << x << ", " << y << ")" << endl;
6 }
7};
8
// Aggregate initialization: the values fill x and y in declaration order
9Point p1 = {3, 4};
10Point p2 = {7, 2};
// Print (3, 4) and then (7, 2)
11p1.print();
12p2.print();

Output

(3, 4)
(7, 2)
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.

  • <× 12
  • ;× 7
  • "× 6
  • ,× 4
  • (× 4
  • )× 4
  • {× 4
  • }× 4
  • .× 2
  • =× 2

More C++ examples at level 4

← C++ typing practice