Classes and Objects
💻 C++Group data and behaviour, control access and write constructors.
A class is the foundation of C++ design. It keeps data private and exposes only the operations that maintain its rules.
- Define a class with private data.
- Write constructors.
- Use const member functions.
A Class
Members are private by default in a class. Expose public methods that preserve the object's rules.
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int score;
public:
Student(std::string name, int score)
: name(std::move(name)), score(score) {}
void addScore(int points) {
if (points > 0) score += points;
}
std::string grade() const {
if (score >= 70) return "A";
if (score >= 60) return "B";
if (score >= 50) return "C";
return "F";
}
const std::string& getName() const {
return name;
}
};Constructors
A constructor sets up a valid object. Use a member initialiser list to initialise fields directly instead of assigning inside the body.
Student student("Amina", 64);
student.addScore(8);
std::cout << student.getName() << ": " << student.grade() << "\n";const Correctness
Mark methods that do not change the object as const. It lets callers use the object through a const reference and documents intent.
Practice
- Create a Book class with title, author and price.
- Add a method that returns a formatted description.
- Reject a negative price in the constructor.
Hands-on exercise
Create a BankAccount class with:
1. A private balance.
2. A constructor that accepts an opening balance.
3. deposit and withdraw methods.
4. withdraw refuses to go below zero.
5. A getBalance method marked const.
Recap
Classes keep data private and expose safe operations. Constructors create valid objects and const methods document read-only behaviour.
Example
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int score;
public:
Student(std::string name, int score)
: name(std::move(name)), score(score) {}
void addScore(int points) {
if (points > 0) score += points;
}
std::string grade() const {
if (score >= 70) return "A";
if (score >= 60) return "B";
if (score >= 50) return "C";
return "F";
}
const std::string& getName() const {
return name;
}
};
Exercises
1. A private balance.
2. A constructor that accepts an opening balance.
3. deposit and withdraw methods.
4. withdraw refuses to go below zero.
5. A getBalance method marked const.
Expected Output
1500
Lesson Nav
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project