Introduction to Classes
In C++, a class serves as a blueprint for creating objects. It encapsulates data and functions that operate on that data, providing a structured approach to object-oriented programming.
Class Definition
Classes are defined using the class keyword:
class MyClass {
// Class members: variables and functions
};
The class body contains member variables (attributes) and member functions (methods).
Access Specifiers and Encapsulation
C++ provides three access specifiers:
public: Accessible from outside the classprivate: Accessible only within the class (default for classes)protected: Similar to private but accessible in derived classes
Encapsualtion bundles data and methods together while controlling access through these specifiers.
Class Scope
Classes create thier own scope. When defining members outside the class, use the scope resolution operator:
void MyClass::memberFunction() {
// Implementation
}
Object Instantiation
Class declarations don't allocate memory. Objects must be instantiated to create instances:
MyClass obj; // Object instantiation
Class Size Calculation
Class size is determined by its member variables (following memory alignment rules), not member functions:
class Sample {
int value;
double number;
};
// Size depends on int and double, plus padding
Empty classes have size 1 byte to ensure unique addressability.
The this Pointer
Each non-static member function receives an implicit this parameter pointing to the current object:
class Example {
int data;
public:
void setData(int data) {
this->data = data; // Distinguish parameter from member
}
};
The this pointer enables member functions too operate on specific object instances.
Practical Considerations
Member variable naming conventions help avoid ambiguity:
class Timer {
int duration_; // Common convention: trailing underscore
public:
void setDuration(int duration) {
duration_ = duration;
}
};