cpp
examples
examples.cpp⚙️cpp
/**
* Classes in C++ - Comprehensive Examples
*
* Demonstrates:
* - Class definition and usage
* - Constructors and destructors
* - this pointer
* - Static members
*
* Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
* Run: ./examples
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// ============================================================
// SECTION 1: BASIC CLASS DEFINITION
// ============================================================
// Simple class with public members
class Rectangle {
public:
int width;
int height;
int area() {
return width * height;
}
int perimeter() {
return 2 * (width + height);
}
};
void demonstrateBasicClass() {
cout << "--- Basic Class ---\n" << endl;
Rectangle rect;
rect.width = 10;
rect.height = 5;
cout << "Rectangle: " << rect.width << " x " << rect.height << endl;
cout << "Area: " << rect.area() << endl;
cout << "Perimeter: " << rect.perimeter() << endl;
}
// ============================================================
// SECTION 2: ACCESS SPECIFIERS
// ============================================================
class BankAccount {
private:
string accountNumber;
double balance;
protected:
string ownerName;
public:
// Constructor
BankAccount(const string& accNum, const string& owner, double initial)
: accountNumber(accNum), balance(initial), ownerName(owner) {}
// Public interface
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrew: $" << amount << endl;
return true;
}
cout << "Withdrawal failed!" << endl;
return false;
}
double getBalance() const { return balance; }
string getOwner() const { return ownerName; }
};
void demonstrateAccessSpecifiers() {
cout << "\n--- Access Specifiers ---\n" << endl;
BankAccount account("123456", "John Doe", 1000.0);
// Can access public members
cout << "Owner: " << account.getOwner() << endl;
cout << "Initial balance: $" << account.getBalance() << endl;
account.deposit(500);
cout << "Balance after deposit: $" << account.getBalance() << endl;
account.withdraw(200);
cout << "Balance after withdrawal: $" << account.getBalance() << endl;
// Cannot access private members:
// account.balance = 1000000; // ERROR!
// cout << account.accountNumber; // ERROR!
}
// ============================================================
// SECTION 3: CONSTRUCTORS
// ============================================================
class Point {
private:
int x, y;
public:
// Default constructor
Point() : x(0), y(0) {
cout << " Default constructor: (" << x << ", " << y << ")" << endl;
}
// Parameterized constructor
Point(int xVal, int yVal) : x(xVal), y(yVal) {
cout << " Parameterized constructor: (" << x << ", " << y << ")" << endl;
}
// Copy constructor
Point(const Point& other) : x(other.x), y(other.y) {
cout << " Copy constructor: (" << x << ", " << y << ")" << endl;
}
// Getters
int getX() const { return x; }
int getY() const { return y; }
void print() const {
cout << " Point(" << x << ", " << y << ")" << endl;
}
};
void demonstrateConstructors() {
cout << "\n--- Constructors ---\n" << endl;
cout << "Creating p1 with default constructor:" << endl;
Point p1;
cout << "\nCreating p2 with parameterized constructor:" << endl;
Point p2(10, 20);
cout << "\nCreating p3 with copy constructor:" << endl;
Point p3 = p2;
cout << "\nCreating p4 with copy constructor (explicit):" << endl;
Point p4(p2);
cout << "\nAll points:" << endl;
p1.print();
p2.print();
p3.print();
p4.print();
}
// Class with multiple constructor options
class Circle {
private:
double radius;
string color;
public:
// Constructor with default values
Circle(double r = 1.0, const string& c = "black")
: radius(r), color(c) {
cout << " Circle created: r=" << radius << ", color=" << color << endl;
}
double getArea() const { return 3.14159 * radius * radius; }
};
void demonstrateDefaultParameters() {
cout << "\n--- Default Parameters in Constructors ---\n" << endl;
cout << "Circle c1; (uses all defaults)" << endl;
Circle c1;
cout << "\nCircle c2(5.0); (radius=5, default color)" << endl;
Circle c2(5.0);
cout << "\nCircle c3(3.0, \"red\"); (both specified)" << endl;
Circle c3(3.0, "red");
}
// ============================================================
// SECTION 4: DESTRUCTORS
// ============================================================
class Resource {
private:
string name;
int* data;
size_t size;
public:
Resource(const string& n, size_t s) : name(n), size(s) {
data = new int[size];
cout << " Resource '" << name << "' created (allocated " << size << " ints)" << endl;
}
~Resource() {
delete[] data;
cout << " Resource '" << name << "' destroyed (freed memory)" << endl;
}
void fill(int value) {
for (size_t i = 0; i < size; i++) {
data[i] = value;
}
}
};
void demonstrateDestructors() {
cout << "\n--- Destructors ---\n" << endl;
cout << "Entering scope:" << endl;
{
Resource r1("Local1", 100);
Resource r2("Local2", 200);
r1.fill(42);
r2.fill(99);
cout << "\n Using resources..." << endl;
cout << "\nLeaving scope:" << endl;
}
cout << "After scope - resources destroyed" << endl;
cout << "\nDynamic allocation:" << endl;
Resource* ptr = new Resource("Dynamic", 50);
cout << " Using dynamic resource..." << endl;
delete ptr;
cout << "After delete" << endl;
}
// ============================================================
// SECTION 5: THIS POINTER
// ============================================================
class Counter {
private:
int value;
public:
Counter(int v = 0) : value(v) {}
// Using 'this' to disambiguate
void setValue(int value) {
this->value = value; // 'this->' for member variable
}
int getValue() const {
return this->value; // Optional here, but explicit
}
// Method chaining using *this
Counter& add(int n) {
value += n;
return *this;
}
Counter& subtract(int n) {
value -= n;
return *this;
}
Counter& multiply(int n) {
value *= n;
return *this;
}
void print() const {
cout << "Value: " << value << endl;
}
};
void demonstrateThisPointer() {
cout << "\n--- this Pointer ---\n" << endl;
Counter c(10);
cout << "Initial value: " << c.getValue() << endl;
c.setValue(5);
cout << "After setValue(5): " << c.getValue() << endl;
// Method chaining
cout << "\nMethod chaining:" << endl;
cout << "Starting with 10, add(5).subtract(3).multiply(2):" << endl;
Counter chain(10);
chain.add(5).subtract(3).multiply(2);
chain.print(); // (10 + 5 - 3) * 2 = 24
}
// ============================================================
// SECTION 6: STATIC MEMBERS
// ============================================================
class Student {
private:
string name;
int id;
static int nextId; // Shared counter
static int totalCount; // Total students created
public:
Student(const string& n) : name(n), id(nextId++) {
totalCount++;
cout << " Student '" << name << "' enrolled with ID: " << id << endl;
}
~Student() {
totalCount--;
cout << " Student '" << name << "' (ID: " << id << ") left" << endl;
}
// Static methods
static int getTotalCount() { return totalCount; }
static int getNextId() { return nextId; }
string getName() const { return name; }
int getId() const { return id; }
};
// Define static members (required outside class)
int Student::nextId = 1000;
int Student::totalCount = 0;
void demonstrateStaticMembers() {
cout << "\n--- Static Members ---\n" << endl;
cout << "Initial state:" << endl;
cout << " Total students: " << Student::getTotalCount() << endl;
cout << " Next ID: " << Student::getNextId() << endl;
cout << "\nEnrolling students:" << endl;
{
Student s1("Alice");
Student s2("Bob");
Student s3("Charlie");
cout << "\nAfter 3 enrollments:" << endl;
cout << " Total students: " << Student::getTotalCount() << endl;
cout << " Next ID: " << Student::getNextId() << endl;
cout << "\nLeaving scope:" << endl;
}
cout << "\nAfter scope:" << endl;
cout << " Total students: " << Student::getTotalCount() << endl;
cout << " Next ID: " << Student::getNextId() << " (preserved)" << endl;
}
// Static utility class (all static members)
class MathUtils {
public:
static constexpr double PI = 3.14159265359;
static constexpr double E = 2.71828182845;
static double circleArea(double radius) {
return PI * radius * radius;
}
static double circleCircumference(double radius) {
return 2 * PI * radius;
}
static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// Delete constructor to prevent instantiation
MathUtils() = delete;
};
void demonstrateStaticUtilityClass() {
cout << "\n--- Static Utility Class ---\n" << endl;
cout << "PI = " << MathUtils::PI << endl;
cout << "E = " << MathUtils::E << endl;
cout << "Circle area (r=5): " << MathUtils::circleArea(5) << endl;
cout << "Circle circumference (r=5): " << MathUtils::circleCircumference(5) << endl;
cout << "5! = " << MathUtils::factorial(5) << endl;
// Cannot create instance:
// MathUtils m; // ERROR!
}
// ============================================================
// SECTION 7: CONST METHODS AND OBJECTS
// ============================================================
class ImmutablePoint {
private:
int x, y;
public:
ImmutablePoint(int xVal, int yVal) : x(xVal), y(yVal) {}
// Const methods - promise not to modify object
int getX() const { return x; }
int getY() const { return y; }
double distanceFromOrigin() const {
return sqrt(x * x + y * y);
}
// Non-const method - can modify object
void move(int dx, int dy) {
x += dx;
y += dy;
}
void print() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
void demonstrateConstMethods() {
cout << "\n--- Const Methods ---\n" << endl;
// Non-const object - can call any method
ImmutablePoint p1(3, 4);
cout << "Non-const point: ";
p1.print();
cout << "Distance from origin: " << p1.distanceFromOrigin() << endl;
p1.move(2, 1);
cout << "After move(2, 1): ";
p1.print();
// Const object - can only call const methods
const ImmutablePoint p2(6, 8);
cout << "\nConst point: ";
p2.print();
cout << "Distance from origin: " << p2.distanceFromOrigin() << endl;
// p2.move(1, 1); // ERROR! Cannot call non-const method on const object
}
// ============================================================
// SECTION 8: COMPLETE CLASS EXAMPLE
// ============================================================
class Book {
private:
string title;
string author;
int pages;
double price;
bool available;
static int totalBooks;
public:
// Default constructor
Book() : title("Unknown"), author("Unknown"), pages(0),
price(0.0), available(true) {
totalBooks++;
}
// Parameterized constructor
Book(const string& t, const string& a, int p, double pr)
: title(t), author(a), pages(p), price(pr), available(true) {
totalBooks++;
}
// Copy constructor
Book(const Book& other)
: title(other.title), author(other.author), pages(other.pages),
price(other.price), available(other.available) {
totalBooks++;
cout << " (Book copied: " << title << ")" << endl;
}
// Destructor
~Book() {
totalBooks--;
}
// Getters (const)
string getTitle() const { return title; }
string getAuthor() const { return author; }
int getPages() const { return pages; }
double getPrice() const { return price; }
bool isAvailable() const { return available; }
// Setters
void setPrice(double p) {
if (p >= 0) price = p;
}
void checkout() {
if (available) {
available = false;
cout << " " << title << " checked out" << endl;
} else {
cout << " " << title << " is not available" << endl;
}
}
void returnBook() {
available = true;
cout << " " << title << " returned" << endl;
}
// Display info
void display() const {
cout << " \"" << title << "\" by " << author << endl;
cout << " Pages: " << pages << ", Price: $" << price;
cout << ", Status: " << (available ? "Available" : "Checked out") << endl;
}
// Static method
static int getTotalBooks() { return totalBooks; }
};
int Book::totalBooks = 0;
void demonstrateCompleteClass() {
cout << "\n--- Complete Class Example: Book ---\n" << endl;
cout << "Creating books:" << endl;
Book book1("The Great Gatsby", "F. Scott Fitzgerald", 180, 15.99);
Book book2("1984", "George Orwell", 328, 12.99);
Book book3; // Default constructor
cout << "\nLibrary inventory (" << Book::getTotalBooks() << " books):" << endl;
book1.display();
book2.display();
book3.display();
cout << "\nOperations:" << endl;
book1.checkout();
book1.checkout(); // Try again
book1.returnBook();
book2.setPrice(9.99);
cout << " Updated 1984 price: $" << book2.getPrice() << endl;
cout << "\nCopying a book:" << endl;
Book book4 = book1;
cout << "Total books after copy: " << Book::getTotalBooks() << endl;
}
// ============================================================
// MAIN FUNCTION
// ============================================================
int main() {
cout << "╔════════════════════════════════════════════════════════════════════╗" << endl;
cout << "║ C++ CLASSES - EXAMPLES ║" << endl;
cout << "║ Fundamentals of Object-Oriented Programming ║" << endl;
cout << "╚════════════════════════════════════════════════════════════════════╝" << endl;
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 1: Basic Class Definition ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateBasicClass();
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 2: Access Specifiers ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateAccessSpecifiers();
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 3: Constructors ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateConstructors();
demonstrateDefaultParameters();
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 4: Destructors ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateDestructors();
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 5: this Pointer ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateThisPointer();
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 6: Static Members ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateStaticMembers();
demonstrateStaticUtilityClass();
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 7: Const Methods ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateConstMethods();
cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
cout << "║ SECTION 8: Complete Class Example ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
demonstrateCompleteClass();
cout << "\n╔════════════════════════════════════════════════════════════════════╗" << endl;
cout << "║ Examples Complete! ║" << endl;
cout << "╚════════════════════════════════════════════════════════════════════╝" << endl;
return 0;
}