Class definition in C++

Level 4164 keystrokes

Defines a Person class with public members and a method, then creates an object, sets its members and calls the method.

C++ code

// Define a new type named Person
1class Person {
// Members below can be accessed from outside the class
2public:
// Data members: each object has its own name and age
3 string name;
4 int age;
5
// Member function that uses the object's own data
6 void introduce() {
// Print e.g. "Alice is 25"
7 cout << name << " is " << age << endl;
8 }
// A class definition must end with a semicolon
9};
10
// Create a Person object on the stack
11Person p;
// Assign the public members with the dot operator
12p.name = "Alice";
13p.age = 25;
// Call the method, which prints "Alice is 25"
14p.introduce();

Output

Alice is 25
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.

  • ;× 8
  • <× 8
  • "× 4
  • .× 3
  • (× 2
  • )× 2
  • {× 2
  • }× 2
  • =× 2
  • :× 1

More C++ examples at level 4

← C++ typing practice