Classes & Objects
Overview
If you want to build a house, you don't just start nailing wood together. You hire an architect to draw a Blueprint. In C++, a class is the Blueprint. It is a user-defined template that describes exactly what a 'House' should look like (variables) and what it can do (functions).
However, you cannot live inside a blueprint. To use it, you must build a physical manifestation of it in memory. This physical manifestation is called an Object (or an 'Instance'). You can use one class (blueprint) to stamp out thousands of unique Objects in your RAM, each with their own distinct data.
Syntax
// 1. THE BLUEPRINT (Class)
class Player {
public: // (We will cover access modifiers next!)
// Attributes (Data)
std::string name;
int health;
// Methods (Behavior)
void heal() {
health += 10;
}
};
int main() {
// 2. THE OBJECT (Instantiating the class in memory)
Player p1;
// 3. Interacting with the Object using the Dot Operator (.)
p1.name = "Arthur";
p1.health = 50;
p1.heal(); // health is now 60!
return 0;
}Common Pitfalls
- Forgetting the trailing semicolon. Just like a
struct, the physical definition of aclassabsolutely MUST end with a semicolon};. If you forget this, the C++ compiler will throw hundreds of unrelated errors on the code below it, totally confusing you.
Interview Questions
class is defined?No. A class is purely a conceptual blueprint for the compiler. Absolutely zero memory is allocated for variables when a class is written. Memory is only physically allocated when the class is instantiated into an Object.
Real-World Example
Using a single blueprint to stamp out multiple independent objects.
#include <iostream>
#include <string>
class Car {
public:
std::string brand;
int speed;
};
int main() {
// Two physically distinct objects in memory
Car car1;
car1.brand = "Ferrari";
car1.speed = 200;
Car car2;
car2.brand = "Toyota";
car2.speed = 120;
std::cout << car1.brand << " is faster than " << car2.brand << "\n";
return 0;
}Check Your Knowledge
Test your understanding of Classes & Objects with these quick questions.