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:

(2) 1.2 Why Do We Need Classes?

Without classes (using structs, with limitations):

CPP
#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):

CPP
#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

CPP
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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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:

CPP
#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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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 ⭐⭐⭐)

CPP 📖 Display only
#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;
}
47 logic lines (exceeds 40-line limit, display only)

Output:

TEXT 📖 Display only
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:

TEXT 📖 Display only
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

Q Can constructors be overloaded?
A Yes! You can define multiple constructors (with different parameters).


📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Define a Book class with three private members: title, author, and price.

  2. Provide public setter and getter methods

  3. Create two Book objects in main and output their information

  4. Intermediate (Difficulty ⭐⭐): Define a Rectangle class with two private members: width and height.

  5. Provide a parameterized constructor

  6. Provide double getArea() and double getPerimeter() member functions

  7. Test in main

  8. Challenge (Difficulty ⭐⭐⭐): Define a Date class with three private members: year, month, and day.

  9. Provide a parameterized constructor

  10. Provide a bool isValid() member function (checks if the date is valid)

  11. Provide a void print() member function (outputs the date in format: 2024-02-29)

  12. 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)!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏