A class is a user-defined blueprint that bundles data (attributes) and behavior (methods) into one unit. Classes are the foundation of Object-Oriented Programming (OOP).
Note: The class definition ends with a semicolon; — this is a common mistake to forget!
Exercise
Create a Person class with attributes name (string) and age (int), and a method introduce() that prints "Hi, I'm [name] and I'm [age] years old." Create two Person objects and call their method.
Show Solution
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
void introduce() {
cout << "Hi, I'm " << name << " and I'm " << age << " years old." << endl;
}
};
int main() {
Person p1; p1.name = "Alice"; p1.age = 28; p1.introduce();
Person p2; p2.name = "Bob"; p2.age = 34; p2.introduce();
return 0;
}
Quiz
What does a class definition end with?
A) A closing brace only
B) A semicolon after the closing brace
C) A period
D) The keyword end
Answer
B) A semicolon — };
What term describes the functions defined inside a class?
A) Properties
B) Attributes
C) Methods
D) Modules
Answer
C) Methods
Summary
A class is a blueprint combining data and behavior.
Class members are accessed using the dot operator ..