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:
- First member at offset 0
- Subsequent members aligned to their size
- 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:
- Is constant (cannot be reassigned)
- Is only accessible within member functions
- Is passed automatically by the compiler
- Can be explicitly referenced within method bodies
class Example {
int value;
void setValue(int value) {
this->value = value; // Disambiguates member from parameter
}
};