C++ Classes
In this section, we will discuss the basics of object-oriented programming (OOP) in C++. A class represents a set of functions (i.e., methods) and data for those methods. An object is an instance of a class.
- Class variables
- Methods
- Encapsulation:
- Polymorphism
- Inheritance
- Operator overloading
Defining a Class
In C++, a class is a user-defined data type that combines data members (variables) and member functions (methods) into a single unit. Classes serve as blueprints for creating objects. Here's a simple example of defining a class in C++:
#include <iostream>
using namespace std;
class Rectangle {
public:
// Data members
double length;
double width;
// Member functions
double area() {
return length * width;
}
double perimeter() {
return 2 * (length + width);
}
};
Constructors
Constructors are special member functions used to initialize objects of a class. Here's an example of a constructor for the Rectangle class:
Rectangle::Rectangle(double l, double w) {
length = l;
width = w;
}
// Usage
int main() {
Rectangle r(5.0, 3.0); // Creating a Rectangle object with specified dimensions
cout << "Area: " << r.area() << endl;
cout << "Perimeter: " << r.perimeter() << endl;
return 0;
}
Destructor
In C++, a destructor is a special member function that gets called when an object goes out of scope or is explicitly deleted. Here's an example:
Rectangle::~Rectangle() {
cout << "Rectangle object destroyed" << endl;
}
// Usage
int main() {
Rectangle r(5.0, 3.0);
// r goes out of scope here, and the destructor is called automatically
return 0;
}
Operator Overloading
Operator overloading allows you to define how operators like +, -, *, and others behave with objects of your class. Here's an example of overloading the + operator for the Rectangle class:
Rectangle operator+(const Rectangle& r1, const Rectangle& r2) {
Rectangle result;
result.length = r1.length + r2.length;
result.width = r1.width + r2.width;
return result;
}
// Usage
int main() {
Rectangle r1(5.0, 3.0);
Rectangle r2(2.0, 4.0);
Rectangle sum = r1 + r2; // Using the overloaded + operator
cout << "Sum of rectangles: Area=" << sum.area() << ", Perimeter=" << sum.perimeter() << endl;
return 0;
}
Assignment Operators
In C++, you can overload assignment operators (=, +=, -=) to define custom behavior for objects of your class during assignment. This allows you to control how your objects are copied or modified.
Example:
class MyNumber {
private:
int value;
public:
MyNumber(int v) : value(v) {}
// Overloading the assignment operator '='
MyNumber& operator=(const MyNumber& other) {
if (this == &other) // Self-assignment check
return *this;
value = other.value;
return *this;
}
};
In this example, we overload the assignment operator to ensure that self-assignment is handled gracefully.