C++ Classes, Objects, and Memory Allocation Techniques

Udnerstanding Classes and Objects

In C++ programming, classes serve as blueprints for creating custom data structures. A class encapsulates data members and member functions that operate on that data.

Objects represent concrete instances of classes. Each object maintains its own unique state while sharing the same structural definition provided by its class.

Basic Class Implementation

#include <iostream>
#include <string>

class Employee {
private:
    std::string employeeName;
    int workExperience;

public:
    // Constructor with parameter initialization
    Employee(const std::string& name, int years) : employeeName(name), workExperience(years) {}

    // Accessor methods
    void updateName(const std::string& name) {
        employeeName = name;
    }

    std::string retrieveName() const {
        return employeeName;
    }

    void updateExperience(int years) {
        workExperience = years;
    }

    int retrieveExperience() const {
        return workExperience;
    }

    void showDetails() const {
        std::cout << "Employee: " << employeeName 
                  << ", Experience: " << workExperience 
                  << " years" << std::endl;
    }
};

int main() {
    // Stack-based instantiation
    Employee worker1("John Smith", 5);
    Employee worker2("Jane Doe", 8);

    worker1.showDetails();
    worker2.showDetails();

    // Modify object properties
    worker1.updateName("Jonathan Smith");
    worker1.updateExperience(6);

    worker1.showDetails();

    return 0;
}

Object Instantiation Methods

C++ provides multiple approaches for object creation, each with distinct memory management characteristics.

1. Stack Allocation

This method provides automatic memory management. The object is automatically destroyed when it goes out of scope.

#include <iostream>

class DataProcessor {
public:
    DataProcessor(int id) : identifier(id) {
        std::cout << "Processor created with ID: " << identifier << std::endl;
    }

    ~DataProcessor() {
        std::cout << "Processor destroyed with ID: " << identifier << std::endl;
    }

    void executeTask() const {
        std::cout << "Processing task for ID: " << identifier << std::endl;
    }

private:
    int identifier;
};

int main() {
    DataProcessor processor(100);
    processor.executeTask();
    return 0;
}

2. Heap Allocation

Manual memory management using new and delete operators. Requires careful handling to prevent memory leaks.

#include <iostream>

class NetworkSession {
public:
    NetworkSession(int port) : connectionPort(port) {
        std::cout << "Session established on port: " << connectionPort << std::endl;
    }

    ~NetworkSession() {
        std::cout << "Session closed on port: " << connectionPort << std::endl;
    }

    void showStatus() const {
        std::cout << "Active connection at port: " << connectionPort << std::endl;
    }

private:
    int connectionPort;
};

int main() {
    NetworkSession* session = new NetworkSession(8080);
    session->showStatus();
    delete session;
    return 0;
}

3. Smart Pointer Allocation

Modern C++ uses smart pointers for automatic memory management. Two primary implementations:

  • std::unique_ptr - Exclusive ownership model
  • std::shared_ptr - Shared ownership with reference countnig

Unique Ownership Example

#include <iostream>
#include <memory>

class DatabaseConnection {
public:
    DatabaseConnection(int id) : connectionId(id) {
        std::cout << "DB connection established: " << connectionId << std::endl;
    }

    ~DatabaseConnection() {
        std::cout << "DB connection terminated: " << connectionId << std::endl;
    }

    void query() const {
        std::cout << "Executing query on connection: " << connectionId << std::endl;
    }

private:
    int connectionId;
};

int main() {
    auto dbConnection = std::make_unique<DatabaseConnection>(5);
    dbConnection->query();
    return 0;
}

Shared Ownership Example

#include <iostream>
#include <memory>

class ResourceHandle {
public:
    ResourceHandle(int id) : resourceId(id) {
        std::cout << "Resource allocated: " << resourceId << std::endl;
    }

    ~ResourceHandle() {
        std::cout << "Resource released: " << resourceId << std::endl;
    }

    void use() const {
        std::cout << "Using resource: " << resourceId << std::endl;
    }

private:
    int resourceId;
};

int main() {
    std::shared_ptr<ResourceHandle> firstRef = std::make_shared<ResourceHandle>(10);
    {
        std::shared_ptr<ResourceHandle> secondRef = firstRef;
        secondRef->use();
    } // Reference count decreases but resource remains
    firstRef->use();
    return 0;
}

Tags: C++ OOP Classes Objects Memory Management

Posted on Tue, 19 May 2026 20:54:44 +0000 by Bike Racer