Object Oriented Programming in C++

Object Oriented Programming in C++

What is Object Oriented Programming (OOP)

Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and code that operates on that data. OOP languages like C++ are designed to be more intuitive and efficient for programming, as they allow developers to organize their code in a way that reflects the structure of the problem they are trying to solve.

How OOP works in C++

In C++, objects are created from "classes". A class is a blueprint for an object, and it defines the data and behavior that an object of that class will have. For example, consider the following simple class definition in C++:

class Circle { 
  public:
    double radius; 
    double getArea(); 
};

This class defines a Circle object that has a data member radius and a member function getArea(), which calculates and returns the area of the circle.

To create an object of this class, we can use the following syntax:

Circle c;

This creates an object c of type Circle. We can then access the data members and member functions of the object using the "dot" notation:

c.radius = 5.0;
double area = c.getArea();

Constructors and Destructors in OOP

In addition to data members and member functions, a class can also have constructors and destructors. A constructor is a special function that is called when an object of the class is created, and it is used to initialize the object's data members. A destructor is a special function that is called when an object goes out of scope or is otherwise destroyed, and it is used to perform any necessary cleanup tasks.

Here is an example of a class with a constructor and a destructor:

class Circle
{
  public:
    double radius;
    Circle(double r); // Constructor
    ~Circle(); // Destructor
    double getArea();
};

Circle::Circle(double r)
{ 
  radius = r; 
}

Circle::~Circle()
{ 
  // Perform cleanup tasks 
}

OOP also allows for the concept of inheritance, which allows one class to inherit the data and behavior of another class. For example, consider the following class hierarchy:

           Shape
           /     \
      Circle     Rectangle

Here, the Circle and Rectangle classes both inherit from the Shape class. This means that they can inherit data members and member functions from the Shape class, and they can also have their own data members and member functions that are specific to their class.

Here is an example of how this might look in C++:

class Shape
{
  public:
    double x, y;
    void move(double dx, double dy);
};

class Circle :
public Shape
{
  public:
    double radius;
    double getArea();
};

class Rectangle : 
public Shape
{
  public:
    double width, height;
    double getArea();
};

I hope this helps to give you an understanding of OOP in C++!

Please let me know if you have any query or suggestion.