"An in-depth exploration of C++, its features, and the principles of Object-Oriented Programming."
By Samir Niroula
27 October 2024C++ is a high-performance language developed by Bjarne Stroustrup. It builds on C and introduces object-oriented programming (OOP) features.
C++ enhances C with classes, polymorphism, and more. It has evolved through standards like C++98, C++11, and C++20.
Low-level memory access for optimized performance.
Code runs on multiple platforms with minimal changes.
Rich library with data structures, algorithms, and STL.
Supports procedural, OOP, and generic programming.
if, switch.for, while.break, return.Reusable code blocks with parameters and return values.
Direct memory access and dynamic memory management.
Blueprints for creating objects with attributes and methods.
class Car {
public:
string brand;
string model;
int year;
void display() {
cout << brand << " " << model << " (" << year << ")" << endl;
}
};Inheritance allows a class (derived class) to inherit attributes and methods from another class (base class). This promotes code reusability and establishes a natural hierarchy.
class Vehicle {
public:
string brand;
void honk() {
cout << "Beep beep!" << endl;
}
};
class Car : public Vehicle {
public:
string model;
int year;
void display() {
cout << brand << " " << model << " (" << year << ")" << endl;
}
};Polymorphism enables functions to process objects differently based on their data type or class. It can be achieved through function overloading, operator overloading, and virtual functions.
class Animal {
public:
virtual void sound() {
cout << "Some generic animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Woof!" << endl;
}
};Encapsulation restricts direct access to some of an object's components, which can prevent the accidental modification of data. It is achieved using access specifiers: private, protected, and public.
class Box {
private:
double length;
double width;
double height;
public:
void setDimensions(double l, double w, double h) {
length = l;
width = w;
height = h;
}
double getVolume() {
return length * width * height;
}
};Abstraction simplifies complex systems by modeling classes appropriate to the problem, and working at the most relevant level of inheritance for a particular aspect of the problem.
class AbstractDevice {
public:
virtual void turnOn() = 0; // Pure virtual function
virtual void turnOff() = 0;
};
class Fan : public AbstractDevice {
public:
void turnOn() override {
cout << "Fan is on" << endl;
}
void turnOff() override {
cout << "Fan is off" << endl;
}
};