C++ Classes and Object-Oriented Principles

Class Fundamentals

In C++, the class keyword introduces a user-defined type that bundles data members (attributes) and member functions (methods). The four foundational pillars of Object-Oriented Programming (OOP) are encapsulation, inheritance, abstraction, and polymorphism.

An interesting memory allocation detail involves empty classes. When a class lacks any data members or virtual functions, the compiler allocates a size of 1 byte. This ensures distinct memory addresses for distinct instances, allowing successful instantiation. Once actual data members are introduced, this placeholder byte is replaced by the actual required storage.

class Vacant {
    // No members
};

int main() {
    std::cout << "Size of Vacant: " << sizeof(Vacant) << std::endl; // Outputs 1
    return 0;
}

Object-Oriented Paradigm

C++ leverages OOP by modeling real-world problems as interacting objects. By analyzing a domain, developers extract essential characteristics and behaviors into a generalized blueprint. For instance, modeling a geometric disk involves identifying its radius as the core attribute. Calculating derived properties—such as the perimeter or area—remains consistent across all instances, making them ideal candidates for member functions. By exposing only the necessary public interfaces, the internal representation remains protected.

#include <iostream>

constexpr double PI_VAL = 3.14159;

class Disk {
public:
    Disk(double radius) : m_radius(radius) {}

    double fetchDiameter() const { return 2.0 * m_radius; }
    double fetchPerimeter() const { return 2.0 * PI_VAL * m_radius; }
    double fetchArea() const { return PI_VAL * m_radius * m_radius; }

private:
    double m_radius;
};

int main() {
    Disk firstDisk(5.0);
    Disk secondDisk(10.0);

    std::cout << "Diameters: " << firstDisk.fetchDiameter() << ", " << secondDisk.fetchDiameter() << std::endl;
    std::cout << "Perimeters: " << firstDisk.fetchPerimeter() << ", " << secondDisk.fetchPerimeter() << std::endl;
    std::cout << "Areas: " << firstDisk.fetchArea() << ", " << secondDisk.fetchArea() << std::endl;

    return 0;
}

Tags: C++ Object-Oriented Programming Classes

Posted on Sat, 04 Jul 2026 16:43:55 +0000 by nareshrevoori