C++ Programming

Object-Oriented Programming (Classes)

Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.

On this page

Object-Oriented Programming (Classes)

Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects and classes. It's one of the most important concepts in modern C++.

What is OOP?

Object-Oriented Programming models real-world entities as objects that have:

  • Attributes (data/state)
  • Behaviors (functions/methods)

Key Principles:

  • Encapsulation: Bundling data and methods together
  • Abstraction: Hiding implementation details
  • Inheritance: Creating new classes from existing ones
  • Polymorphism: Same interface, different implementations

What is a Class?

A class is a blueprint or template for creating objects. It defines:

  • Data members (attributes/variables)
  • Member functions (methods/behaviors)

Analogy: A class is like a blueprint for a house, and objects are the actual houses built from that blueprint.

Class Syntax

Basic Structure:

1class ClassName {
2private:
3    // Private members (only accessible within class)
4    
5public:
6    // Public members (accessible from outside)
7    
8protected:
9    // Protected members (accessible in class and derived classes)
10};

Access Specifiers

Control who can access class members:

  • private: Only accessible within the class (default)
  • public: Accessible from anywhere
  • protected: Accessible in class and derived classes

Creating a Simple Class

Example:

1class Rectangle {
2private:
3    double width;
4    double height;
5    
6public:
7    // Constructor
8    Rectangle(double w, double h) {
9        width = w;
10        height = h;
11    }
12    
13    // Member functions
14    double getArea() {
15        return width * height;
16    }
17    
18    double getPerimeter() {
19        return 2 * (width + height);
20    }
21    
22    void setDimensions(double w, double h) {
23        width = w;
24        height = h;
25    }
26};

Objects

An object is an instance of a class:

1Rectangle rect(5.0, 3.0);  // Create object
2double area = rect.getArea();  // Call method

Constructors

Constructors initialize objects when they're created.

Default Constructor

No parameters:

1class Rectangle {
2private:
3    double width, height;
4    
5public:
6    Rectangle() {  // Default constructor
7        width = 0;
8        height = 0;
9    }
10};

Parameterized Constructor

Takes parameters:

1Rectangle(double w, double h) {
2    width = w;
3    height = h;
4}

Constructor Initialization List (Preferred)

More efficient:

1Rectangle(double w, double h) : width(w), height(h) {
2    // Body can be empty
3}

Copy Constructor

Creates object from another object:

1Rectangle(const Rectangle& other) {
2    width = other.width;
3    height = other.height;
4}

Destructors

Clean up when object is destroyed:

1~Rectangle() {
2    // Cleanup code (if needed)
3    // Called automatically when object goes out of scope
4}

Note: Destructor name starts with ~ and has no parameters.

Member Functions

Functions defined inside a class:

Inside Class Definition

1class Rectangle {
2public:
3    double getArea() {
4        return width * height;
5    }
6};

Outside Class Definition

1class Rectangle {
2public:
3    double getArea();  // Declaration
4};
5 
6double Rectangle::getArea() {  // Definition
7    return width * height;
8}

this Pointer

Points to the current object:

1class Rectangle {
2private:
3    double width;
4    
5public:
6    void setWidth(double width) {
7        this->width = width;  // this->width refers to member
8    }
9};

Complete Example

1#include <iostream>
2#include <string>
3using namespace std;
4 
5class Student {
6private:
7    string name;
8    int age;
9    double gpa;
10    
11public:
12    // Constructor
13    Student(string n, int a, double g) : name(n), age(a), gpa(g) {}
14    
15    // Getter methods
16    string getName() const { return name; }
17    int getAge() const { return age; }
18    double getGpa() const { return gpa; }
19    
20    // Setter methods
21    void setName(string n) { name = n; }
22    void setAge(int a) { age = a; }
23    void setGpa(double g) { gpa = g; }
24    
25    // Other methods
26    void display() const {
27        cout << "Name: " << name << ", Age: " << age 
28             << ", GPA: " << gpa << endl;
29    }
30    
31    bool isHonorStudent() const {
32        return gpa >= 3.5;
33    }
34};
35 
36int main() {
37    Student student1("Alice", 20, 3.8);
38    Student student2("Bob", 19, 3.2);
39    
40    student1.display();
41    student2.display();
42    
43    if (student1.isHonorStudent()) {
44        cout << student1.getName() << " is an honor student!" << endl;
45    }
46    
47    return 0;
48}

Sample Output

Name: , Age: 
 is an honor student!

Const Member Functions

Functions that don't modify object state:

1double getArea() const {
2    return width * height;  // Cannot modify members
3}

Benefits:

  • Can be called on const objects
  • Clearly indicates function doesn't modify state
  • Better compiler optimization

Static Members

Belong to the class, not individual objects:

Static Data Member

1class Counter {
2private:
3    static int count;  // Shared by all objects
4    
5public:
6    Counter() { count++; }
7    static int getCount() { return count; }
8};
9 
10int Counter::count = 0;  // Definition outside class

Static Member Function

1static int getCount() {
2    return count;  // Can only access static members
3}

Friend Functions

Functions that can access private members:

1class Rectangle {
2private:
3    double width, height;
4    
5    friend void printDimensions(Rectangle& r);
6};
7 
8void printDimensions(Rectangle& r) {
9    cout << r.width << " x " << r.height << endl;
10}

Sample Output

x

Operator Overloading

Define how operators work with your class:

1class Vector {
2private:
3    double x, y;
4    
5public:
6    Vector(double x, double y) : x(x), y(y) {}
7    
8    // Overload + operator
9    Vector operator+(const Vector& other) {
10        return Vector(x + other.x, y + other.y);
11    }
12    
13    // Overload == operator
14    bool operator==(const Vector& other) {
15        return (x == other.x && y == other.y);
16    }
17};
18 
19// Usage
20Vector v1(1, 2);
21Vector v2(3, 4);
22Vector v3 = v1 + v2;  // Uses overloaded +

Best Practices

  1. ✅ Use access specifiers appropriately (private by default)
  2. ✅ Provide constructors for initialization
  3. ✅ Use const for member functions that don't modify state
  4. ✅ Use initialization lists in constructors
  5. ✅ Encapsulate data (make data members private)
  6. ✅ Provide getters/setters when needed
  7. ✅ Keep classes focused (single responsibility)
  8. ✅ Use meaningful names for classes and members

Common Mistakes

  • ❌ Forgetting to initialize members
  • ❌ Not using const for getter functions
  • ❌ Making everything public (breaks encapsulation)
  • ❌ Not providing constructors when needed
  • ❌ Forgetting to define static members outside class
  • ❌ Circular dependencies between classes

Next Steps

In future modules, we'll cover:

  • Inheritance: Creating derived classes
  • Polymorphism: Virtual functions and dynamic binding
  • Abstract Classes: Pure virtual functions
  • Templates: Generic programming

Summary

Classes are the foundation of OOP in C++. They allow you to:

  • Organize related data and functions
  • Create reusable code
  • Model real-world entities
  • Implement encapsulation and abstraction

Master classes, and you'll be ready for advanced OOP concepts!

Hands-on Examples

Basic Class Example

#include <iostream>
#include <string>
using namespace std;

class Rectangle {
private:
    double width;
    double height;
    
public:
    // Constructor
    Rectangle(double w, double h) : width(w), height(h) {}
    
    // Getter methods
    double getWidth() const { return width; }
    double getHeight() const { return height; }
    
    // Setter methods
    void setWidth(double w) { width = w; }
    void setHeight(double h) { height = h; }
    
    // Member functions
    double getArea() const {
        return width * height;
    }
    
    double getPerimeter() const {
        return 2 * (width + height);
    }
    
    void display() const {
        cout << "Rectangle: " << width << " x " << height << endl;
        cout << "Area: " << getArea() << endl;
        cout << "Perimeter: " << getPerimeter() << endl;
    }
};

int main() {
    Rectangle rect(5.0, 3.0);
    rect.display();
    
    rect.setWidth(10.0);
    rect.setHeight(6.0);
    cout << "\nAfter modification:" << endl;
    rect.display();
    
    return 0;
}

Classes bundle data (width, height) and functions (getArea, getPerimeter) together. Private members are encapsulated, public methods provide interface. Constructors initialize objects, getters/setters control access.

Sample Output

Rectangle: 5 x 3
Area: 15
Perimeter: 16

After modification:
Rectangle: 10 x 6
Area: 60
Perimeter: 32