C++ — Classes and Objects
Defining a class
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
// Constructor
Person(string n, int a) : name(n), age(a) {}
// Methods
void greet() const {
cout << "Hi, I'm " << name << "!" << endl;
}
string getName() const { return name; }
int getAge() const { return age; }
};
int main() {
Person alice("Alice", 30);
alice.greet(); // Hi, I'm Alice!
return 0;
}
Access modifiers
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
protected:
string owner;
public:
BankAccount(string o, double b) : owner(o), balance(b) {}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) balance -= amount;
}
double getBalance() const { return balance; }
};
int main() {
BankAccount acc("Alice", 1000);
acc.deposit(500);
cout << "Balance: $" << acc.getBalance() << endl;
// acc.balance = 999999; // Error: private
return 0;
}
Constructors
#include <iostream>
using namespace std;
class Point {
public:
double x, y;
// Default constructor
Point() : x(0), y(0) {}
// Parameterized constructor
Point(double x, double y) : x(x), y(y) {}
// Copy constructor
Point(const Point &other) : x(other.x), y(other.y) {}
void print() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1; // (0, 0)
Point p2(3, 4); // (3, 4)
Point p3(p2); // (3, 4)
p1.print();
p2.print();
p3.print();
return 0;
}
Destructor
#include <iostream>
using namespace std;
class Resource {
private:
string name;
public:
Resource(string n) : name(n) {
cout << "Acquired: " << name << endl;
}
~Resource() {
cout << "Released: " << name << endl;
}
};
int main() {
Resource r1("File");
Resource r2("Socket");
cout << "Using resources..." << endl;
// Destructors called in reverse order when scope ends
return 0;
}
The rule of three/five
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
private:
char *data;
size_t length;
public:
// Constructor
MyString(const char *s) {
length = strlen(s);
data = new char[length + 1];
strcpy(data, s);
}
// Destructor
~MyString() {
delete[] data;
}
// Copy constructor
MyString(const MyString &other) {
length = other.length;
data = new char[length + 1];
strcpy(data, other.data);
}
// Copy assignment operator
MyString &operator=(const MyString &other) {
if (this != &other) {
delete[] data;
length = other.length;
data = new char[length + 1];
strcpy(data, other.data);
}
return *this;
}
void print() const { cout << data << endl; }
};
int main() {
MyString s1("Hello");
MyString s2 = s1; // Copy constructor
s2.print();
return 0;
}
const methods
#include <iostream>
using namespace std;
class Rectangle {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
// Const method — can't modify object
double area() const { return width * height; }
double perimeter() const { return 2 * (width + height); }
// Non-const method
void scale(double factor) {
width *= factor;
height *= factor;
}
};
int main() {
const Rectangle r(5, 3); // Const object
cout << "Area: " << r.area() << endl;
// r.scale(2); // Error: can't call non-const on const object
return 0;
}
Static members
#include <iostream>
using namespace std;
class User {
private:
static int count;
string name;
public:
User(string n) : name(n) { count++; }
~User() { count--; }
static int getCount() { return count; }
void print() const {
cout << name << " (total: " << count << ")" << endl;
}
};
int User::count = 0;
int main() {
User u1("Alice");
User u2("Bob");
u1.print(); // Alice (total: 2)
cout << "Total users: " << User::getCount() << endl;
{
User u3("Charlie");
cout << "Total: " << User::getCount() << endl; // 3
}
cout << "Total: " << User::getCount() << endl; // 2
return 0;
}
Friend functions
#include <iostream>
using namespace std;
class Box {
private:
double width;
public:
Box(double w) : width(w) {}
friend void printWidth(const Box &b);
friend class BoxFactory;
};
void printWidth(const Box &b) {
cout << "Width: " << b.width << endl; // Can access private
}
int main() {
Box box(10.0);
printWidth(box);
return 0;
}
Mini Practice
Write C++ code that:
- Creates a
Rectangleclass with area and perimeter methods - Implements the rule of three for a dynamic array wrapper
- Uses a static member to count instances
- Demonstrates const-correctness with const objects
Up Next
In the next lesson, you'll learn about Constructors — initialization and resource management.
Related Topics
Frequently Asked Questions about Classes and Objects
What is Classes and Objects in C++?
Classes and Objects is a fundamental concept in C++. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Classes and Objects?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Classes and Objects.
Why is Classes and Objects important in C++?
Classes and Objects is essential for C++ development. Understanding this concept will help you write better code and solve real-world problems more effectively.