C++ Classes
intermediatePart of Object-Oriented C++
Theory
Classes in C++ are the foundation of object-oriented programming. They define the blueprint for objects with data members and member functions.
Defining Classes and Constructors
class Point {
private:
double x, y;
public:
Point() : x(0), y(0) {} // Default constructor
Point(double x, double y) : x(x), y(y) {} // Parameterized
double getX() const { return x; }
double getY() const { return y; }
};Initializer lists (: x(x), y(y)) are preferred over assignment in the constructor body — they are more efficient and necessary for const/reference members.
Destructors
A destructor (~ClassName) runs when an object is destroyed. It is essential for RAII — releasing resources automatically:
class FileHandler {
FILE* file;
public:
FileHandler(const char* name) { file = fopen(name, "r"); }
~FileHandler() { if (file) fclose(file); }
};The this Pointer
this is a pointer to the current object instance. It resolves naming conflicts and enables method chaining:
class Person {
std::string name;
public:
Person& setName(const std::string& name) {
this->name = name;
return *this;
}
};Friend Functions
A friend function can access private members of a class even though it is not a member:
Static Members
Static members belong to the class itself, not to individual objects. They must be defined outside the class:
class Counter {
static int count;
public:
Counter() { count++; }
static int getCount() { return count; }
};
int Counter::count = 0;Const Correctness
Mark member functions as const when they don't modify the object. This allows them to be called on const objects and references.
Practical Examples
Exercises
Timer Class with RAII
Create a Timer class that records the time when constructed and prints the elapsed time when destroyed. Use RAII principles.
Expected Output:
Timer elapsed: X.XX seconds