C++ - OOP - Basics

In C++, object-oriented programming (OOP) is a programming paradigm that focuses on organizing code into objects, which are instances of classes. OOP provides a way to structure code, improve code reusability, and model real-world entities. Here are some key concepts of OOP in C++:

Classes and Objects:

A class is a blueprint or template that defines the properties (data members) and behaviors (member functions) of objects. An object is an instance of a class. Classes define the structure and behavior of objects. Here's an example:

class Circle {
private:
    double radius;
public:
    void setRadius(double r) {
        radius = r;
    }
    double getArea() {
        return 3.14159 * radius * radius;
    }
};
int main() {
    Circle c;
    c.setRadius(5.0);
    double area = c.getArea();
    return 0;
}

Encapsulation:

Encapsulation is the process of bundling data and related behaviors into a single unit, i.e., a class. It provides data hiding and protects the internal implementation details of a class from external access. Access specifiers (public, private, protected) control the visibility of members. Private members can only be accessed within the class itself. Public members can be accessed from anywhere. Protected members are accessible within the class and its derived classes.

Inheritance:

Inheritance allows you to create a new class (derived class) from an existing class (base class). The derived class inherits the properties and behaviors of the base class, enabling code reuse and specialization. It supports the "is-a" relationship. Here's an example:

class Shape {
public:
    virtual double getArea() = 0;
};
class Circle : public Shape {
private:
    double radius;
public:
    void setRadius(double r) {
        radius = r;
    }
    double getArea() override {
        return 3.14159 * radius * radius;
    }
};

Polymorphism:

Polymorphism allows objects of different types to be treated as objects of a common base class. It enables you to perform operations on objects without knowing their specific types at compile time. Polymorphism is achieved through function overriding and function overloading. Virtual functions and abstract classes are commonly used for polymorphic behavior.

Abstraction:

Abstraction focuses on hiding unnecessary details and exposing only essential information to the users. It allows you to create abstract classes with pure virtual functions, which serve as interfaces. Concrete classes derived from abstract classes provide implementations for those pure virtual functions.

Polymorphism:

Polymorphism allows objects of different types to be treated as objects of a common base class. It enables you to perform operations on objects without knowing their specific types at compile time. Polymorphism is achieved through function overriding and function overloading. Virtual functions and abstract classes are commonly used for polymorphic behavior.