Understanding Classes and Objects in C++

Classes and Objects in C++

A class in C++ is a user-defined type that encapsulates data (member variables) and functions (member methods) that operate on that data. It serves as a blueprint for creating objects, defining both their beahvior and state.

Class Definition

C++ classes are similar to C structures but with expanded capabilities. While C structures can only contain variables, C++ classes can include both variables and functions. This allows for better organization and differentiation between similar operations in differennt data structures.

#include <iostream>
using namespace std;

class IntegerStack {
    void addElement(int value) {
        // Implementation omitted
    }
    
    void removeElement() {
        // Implementation omitted
    }
    
    int getTopElement() {
        // Implementation omitted
    }
    
    int* storage;
    int topIndex;
    int maxCapacity;
}; // Note the required semicolon

Access Modifiers and Encapsulation

C++ provides three access specifiers:

  • public: Accessible from anywhere
  • private: Accessible only within the class
  • protected: Accessible within the class and derived classes
class SecureStack {
public:
    void insert(int value) {
        // Public method
    }
    
private:
    int* data;
    int currentPosition;
    int totalCapacity;
};

Class Scope

Classes define their own scope. When defining members outside the class, the scope resolution operator (::) specifies the class to which the member belongs.

Object Instantiation

A class can have multiple instances (objects). Each object maintains its own copy of member variables.

int main() {
    SecureStack firstStack;
    SecureStack secondStack;
    
    firstStack.insert(10);
    secondStack.insert(20);
    
    return 0;
}

Memory Allocation for Objects

Object size calculation follows the same rules as structure padding:

  1. First member at offset 0
  2. Subsequent members aligned to their size
  3. Total size is a multiple of the largest alignment requirement

Methods don't contirbute to object size as they're shared across all instances.

class SampleA { // 8 bytes
    int first;
    int second;
};

class SampleB { // 1 byte (minimum size)
    // No member variables
};

The this Pointer

C++ implicitly passes a pointer to the current object (this) to non-static member functions. This pointer:

  1. Is constant (cannot be reassigned)
  2. Is only accessible within member functions
  3. Is passed automatically by the compiler
  4. Can be explicitly referenced within method bodies
class Example {
    int value;
    
    void setValue(int value) {
        this->value = value; // Disambiguates member from parameter
    }
};

Tags: C++ Object-Oriented Programming Classes Objects

Posted on Thu, 29 Oct 2026 16:50:00 +0000 by Pinkerbot