C++: Classes and Objects Basics
Last updated: 2026-08-26
In previous lessons, we used structs to combine variables of different types into a single unit.
But real-world things have not only attributes (like name, age) but also behaviors (like walking, talking).
Classes are used to describe "things" — they encapsulate attributes and behaviors together.
1. What Is a Class?
(1) 1.1 Classes in Everyday Life
| Real-Life Example | Program Equivalent |
|---|---|
| An architectural blueprint (describes the structure of a house) | Class (a template that describes things) |
| A house built from the blueprint (the actual object) | Object (an instance of a class) |
Class vs Object:
- A class is a template (describes what attributes and behaviors a "student" should have)
- An object is an instance (a concrete thing created from the template — the student "Zhang San")
(2) 1.2 Why Do We Need Classes?
Without classes (using structs, with limitations):
#include <iostream>
#include <string>
struct Student {
std::string name;
int age;
double score;
};
int main() {
Student s1 = {"Alice", 20, 92.5};
// ❌ Structs cannot include "behaviors" (like "introduce yourself")
return 0;
}
With classes (complete):
#include <iostream>
#include <string>
class Student {
public:
std::string name;
int age;
double score;
void introduce() {
std::cout << "My name is " << name << ",this year " << age << " years old。" << std::endl;
}
};
int main() {
Student s1;
s1.name = "Alice";
s1.age = 20;
s1.introduce(); // ✅ Classes can include "behaviors"
return 0;
}
2. Class Definition*
(1) 2.1 Basic Syntax
class ClassName {
public:
// members (attributes and behaviors)
};
💡 Key Point: A class definition ends with a semicolon! (Same as structs)
▶ Example 1: Defining a Student Class (Difficulty ⭐)
#include <iostream>
#include <string>
class Student {
public:
// attributes (member variables)
std::string name;
int age;
double score;
// behaviors (member functions)
void introduce() {
std::cout << "My name is " << name << ",this year " << age << " years old。" << std::endl;
}
void study() {
std::cout << name << " is studying..." << std::endl;
}
};
int main() {
Student s1;
s1.name = "Alice";
s1.age = 20;
s1.score = 92.5;
s1.introduce();
s1.study();
return 0;
}
Output:
My name is Alice,this year 20 years old。
Alice is studying...
3. Access Control*
C++ classes have three access levels: public, private, and protected.
(1) 3.1 public vs private*
| Access Level | Accessible Outside the Class? | Purpose |
|---|---|---|
| public | ✅ Yes | Public interface (for external use) |
| private | ❌ No | Internal implementation (hide details) |
Example:
#include <iostream>
#include <string>
class Student {
private:
std::string name; // private member
int age;
public:
// public setter and getter
void setName(const std::string& n) {
name = n;
}
std::string getName() {
return name;
}
};
int main() {
Student s1;
// s1.name = "Alice"; // ERROR: name is private
s1.setName("Alice"); // OK: access via public function
std::cout << s1.getName() << std::endl;
return 0;
}
💡 Encapsulation Principle: Make attributes private, and access them through public setter/getter methods — this lets you control access logic (e.g., checking if age is negative).
4. Constructors*
(1) 4.1 What Is a Constructor?
A constructor is a special function in a class — it is called automatically when an object is created.
| Feature | Description |
|---|---|
| Name | Same as the class name |
| No return value | Not even void |
| Called automatically | Executes when an object is created |
▶ Example 2: Defining a Constructor (Difficulty ⭐⭐)
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
public:
// constructor
Student(const std::string& n, int a) {
name = n;
age = a;
std::cout << "Student Object created: " << name << std::endl;
}
void introduce() {
std::cout << "My name is " << name << ",this year " << age << " years old。" << std::endl;
}
};
int main() {
Student s1("Alice", 20); // OK: constructor called automatically when creating object
s1.introduce();
return 0;
}
Output:
Student Object created: Alice
My name is Alice,this year 20 years old。
5. Destructors*
(1) 5.1 What Is a Destructor?
A destructor is another special function in a class — it is called automatically when an object is destroyed (e.g., when a function ends, or when delete is called).
| Feature | Description |
|---|---|
| Name | ~ClassName |
| No return value | Not even void |
| No parameters | Cannot accept parameters |
| Called automatically | Executes when an object is destroyed |
▶ Example 3: Defining a Destructor (Difficulty ⭐⭐)
#include <iostream>
#include <string>
class Student {
private:
std::string name;
public:
// constructor
Student(const std::string& n) {
name = n;
std::cout << "Constructor: " << name << " created" << std::endl;
}
// destructor
~Student() {
std::cout << "Destructor: " << name << " destroyed" << std::endl;
}
};
int main() {
Student s1("Alice"); // call constructor
// when main() ends, s1 is destroyed, destructor is called
return 0;
}
Output:
Constructor: Alice created
Destructor: Alice destroyed
💡 Usage: Release resources in the destructor (e.g., close files, free dynamic memory).
6. The this Pointer*
(1) 6.1 What Is the this Pointer?
this is a pointer to the current object — inside a member function, this can be used to access the current object.
▶ Example 4: Using this to Distinguish Same-Named Parameters (Difficulty ⭐⭐)
#include <iostream>
#include <string>
class Student {
private:
std::string name;
public:
void setName(const std::string& name) { // WARNING: parameter name same as member variable
this->name = name; // OK: use this-> to access member variable
}
std::string getName() {
return this->name; // OK: this-> can be omitted (recommended to omit)
}
};
int main() {
Student s1;
s1.setName("Alice");
std::cout << s1.getName() << std::endl;
return 0;
}
Output:
Alice
💡 Tip: If the parameter name differs from the member variable name, you don't need this-> (it's recommended to omit it for cleaner code).
7. Practice: Simple Bank Account Class*
▶ Example 5: BankAccount Class (Difficulty ⭐⭐⭐)
#include <iostream>
#include <string>
#include <iomanip>
class BankAccount {
private:
std::string owner;
double balance;
public:
// constructor
BankAccount(const std::string& o, double initialBalance) {
owner = o;
if (initialBalance >= 0) {
balance = initialBalance;
} else {
balance = 0.0;
std::cout << "⚠️ Initial balance cannot be negative, set to 0" << std::endl;
}
}
// deposit
void deposit(double amount) {
if (amount > 0) {
balance += amount;
std::cout << "Deposit successful! +" << amount << std::endl;
} else {
std::cout << "⚠️ Deposit amount must be greater than 0" << std::endl;
}
}
// withdraw
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
std::cout << "Withdrawal successful! -" << amount << std::endl;
} else if (amount <= 0) {
std::cout << "⚠️ Withdrawal amount must be greater than 0" << std::endl;
} else {
std::cout << "⚠️ Insufficient balance" << std::endl;
}
}
// query balance
void queryBalance() {
std::cout << std::fixed << std::setprecision(2);
std::cout << "Account balance: " << balance << " yuan" << std::endl;
}
};
int main() {
BankAccount account("MOTO", 1000.0);
account.queryBalance();
account.deposit(500.0);
account.queryBalance();
account.withdraw(200.0);
account.queryBalance();
account.withdraw(2000.0); // insufficient balance
return 0;
}
Output:
Account balance: 1000.00 yuan
Deposit successful! +500.00
Account balance: 1500.00 yuan
Withdrawal successful! -200.00
Account balance: 1300.00 yuan
⚠️ Insufficient balance
Execution Result:
Account balance: 1000.00 yuan
Deposit successful! +500.00
Account balance: 1500.00 yuan
Withdrawal successful! -200.00
Account balance: 1300.00 yuan
⚠️ Insufficient balance
❓ FAQ
📖 Summary
- Classes: encapsulate data and operations together
- Objects are instances of classes, accessed via . or ->
- Access modifiers: public/protected/private
- Member functions are declared inside the class and can be defined inside or outside
- Constructors: called automatically when an object is created, used for initialization
📝 Exercises
-
Basic (Difficulty ⭐): Define a
Bookclass with three private members: title, author, and price. -
Provide public setter and getter methods
-
Create two
Bookobjects inmainand output their information -
Intermediate (Difficulty ⭐⭐): Define a
Rectangleclass with two private members: width and height. -
Provide a parameterized constructor
-
Provide
double getArea()anddouble getPerimeter()member functions -
Test in
main -
Challenge (Difficulty ⭐⭐⭐): Define a
Dateclass with three private members: year, month, and day. -
Provide a parameterized constructor
-
Provide a
bool isValid()member function (checks if the date is valid) -
Provide a
void print()member function (outputs the date in format:2024-02-29) -
Test in
main
8. 🚀 Next Steps*
Now that you've learned the basics of classes and objects, let's move on to Advanced Constructors (Lesson 29) — default constructors, copy constructors, and move semantics (a C++11 feature)!