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 Person1class Person {// Members below can be accessed from outside the class2public: // Data members: each object has its own name and age3 string name;4 int age;5 // Member function that uses the object's own data6 void introduce() { // Print e.g. "Alice is 25"7 cout << name << " is " << age << endl;8 }// A class definition must end with a semicolon9};10 // Create a Person object on the stack11Person p;// Assign the public members with the dot operator12p.name = "Alice";13p.age = 25;// Call the method, which prints "Alice is 25"14p.introduce();Output
Alice is 25
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