Object Oriented Programming
Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of "objects," which are instances of classes. In C++, OOP is a fundamental feature that facilitates the organization, reuse, and maintenance of code. Classes serve as blueprints for creating objects, encapsulating data and behavior into a single unit. The key principles of OOP in C++ include encapsulation, inheritance, and polymorphism.
Encapsulation involves bundling data and methods that operate on that data within a single class, preventing direct access to internal details and enhancing modularity. Inheritance allows the creation of new classes based on existing ones, promoting code reuse and extensibility. Polymorphism enables the use of a common interface to interact with objects of different types, fostering flexibility in handling diverse data structures.
By employing OOP in C++, developers can achieve modularity, code organization, and enhanced readability. The paradigm supports the creation of well-structured, scalable, and maintainable software systems. Through classes and objects, C++ programmers can design solutions that align with real-world entities and efficiently address complex programming challenges.
C++ programming language was earlier known as C with classes. C++ is an extension of C with support for object oriented programming paradigm. Classes and objects forms the backbone of object oriented programming. The class is one of the defining ideas of object-oriented programming.
- In OOP, we try to model real world entities as classes which contains some specific data and functions.
- Classes provides ability to define your own data types that better correspond to the problem being solved.
- Classes are extension of structures, like structure a class contains data members but can contains member functions.
C++ Classes
A class is a user-defined data type in C++ that encapsulates data members and member functions. The data and functions within a class are called members of the class. A class is like a blueprint from which we can creates instances called objects.
A class is a user defined data type, which specifies the content of the objects and what operations can be performed on such an object.
How to define a class in C++
In C++, a class is defined using keyword class followed by the name of name of class and body of the class. The body of the class defines the data members and member functions. The body of the class is enclosed by a pair of curly braces and terminated by a semicolon at the end.
class class_Name { // data members // member functions };For Example :
class Rectangle { private: int length; public: int width; void setData(int L, int W) { length = L; width = W; } int getArea() { return length * width; } int getPerimeter() { return 2*(length + width); } };
Above class Rectangle has two data members, length and width and three member functions setData, getArea and getPerimeter. We will discuss about the keywords private and public later.
C++ Objects
A class is a user defined data type and on object is an instance of a class. We can think of object as a variable of class. Class definition does not allocate any memory, when we create objects of a class then actually memory gets allocated.
Syntax to Define Objects in C++ The syntax to define object in C++ is same as the syntax of declaring any basic data type of declaring a structure variable.Class_Name Object_Name;For Example :
Rectangle rectangel_one;Object rectagle_one will have its copy of data member and member function as defined in class definition.
Accessing the Data and Member Function of Objects in C++
The public data members and member functions can be accessed by inserting a dot (.) operator between object name and member name. The syntax is same as accessing the members of a structure variable.
For Example :rectangle_one.getArea(); rectangle_one.width();We can only access public members of class from outside of class, private members can only be accessed from with class.
C++ Classes and Object Example Program
#include <iostream> using namespace std; class Rectangle { private: int length; public: int width; void setData(int L, int W) { length = L; width = W; } int getArea() { return length * width; } int getPerimeter() { return 2*(length + width); } }; int main() { int L, W; Rectangle rectange_one; cout << "Enter length and width of rectangle\n"; cin >> L >> W; // calling member functions of class rectange_one.setData(L, W); cout << "Area of Rectangle : " << rectange_one.getArea(); cout << "\nPerimiter of Rectangle : " << rectange_one.getPerimeter(); // Accessing public data member of class cout << "\nWidth : " << rectange_one.width; // We cannot access private member "length" from here return 0; }Output
Enter length and width of rectangle 4 6 Area of Rectangle : 24 Perimiter of Rectangle : 20 Width : 6
Advantages of Classes and Objects in C++
- Encapsulation : Classes encapsulate data and behavior into a single unit, preventing direct access to internal details. This enhances modularity by hiding implementation complexities.
- Separation of Concerns : Classes allow you to separate different aspects of a system into distinct entities. Each class is responsible for a specific functionality, promoting a cleaner and more organized codebase.
- Inheritance : Inheritance enables the creation of new classes based on existing ones, inheriting their attributes and behaviors. This promotes code reuse and reduces redundancy.
- Polymorphism : Polymorphism allows the use of a common interface to work with different types of objects. This flexibility supports extensibility and adaptability to changes in requirements.
- Access Control : Access specifiers (public, private, protected) in classes control the visibility of members, safeguarding data from unauthorized access. This enhances data security and reduces the risk of unintended modifications.
- Data Hiding : Encapsulation hides the internal details of a class, exposing only what is necessary. This prevents direct manipulation of data and ensures that changes to the implementation do not affect external code.
- Readability and Maintainability : Classes provide a clear structure and hierarchy, improving code readability. This, in turn, facilitates easier maintenance and debugging.
- Code Organization : Well-organized code with classes and objects allows developers to quickly locate and understand different components. This accelerates the debugging and maintenance processes.
Passing and Returning Object from Function
Passing objects to a function in C++ is similar to passing a structure or union variable. In C++, Objects are passed using call by value. The called function must declare an object as a formal parameter.
C++ Program to Pass Object to Function
#include <iostream> using namespace std; class Point { private: int x_cor, y_cor; public: Point(int x, int y) { x_cor = x; y_cor = y; } int getX(){ return x_cor; } int getY(){ return y_cor; } }; void drawLine(Point p1, Point p2) { cout << "Drawing line from point (" << p1.getX() << "," << p1.getY() << ") To (" << p2.getX() << "," << p2.getY() << ")"; } int main() { Point p1(2,3), p2(6,7); // Passing p1 and P2 to function drawLine drawLine(p1, p2); return 0; }Output
Drawing line from point (2,3) To (6,7)
In above program, we are creating two objects p1 and p2 of Point class by passing some initial values to constructors. Then we passed p1 and p2 to function drawLine, like passing variables of any other basic data types. Now, inside drawLine function we can access all public member variables and member functions.
Returning Objects from a Function in C++
Returning an object from a function is similar to returning a structure or union variable. Function returning object must declare it's return type as object.
C++ Program to Return Object from a Function
#include <iostream> using namespace std; class Point { private: int x_cor, y_cor; public: Point(){ } Point(int x, int y) { x_cor = x; y_cor = y; } void setPoint(int x, int y) { x_cor = x; y_cor = y; } int getX(){ return x_cor; } int getY(){ return y_cor; } }; Point getMidPoint(Point p1, Point p2) { Point mid; mid.setPoint((p1.getX() + p2.getX())/2, (p1.getY() + p2.getY())/2); return mid; } int main() { Point p1(2,3), p2(6,7), p3; p3 = getMidPoint(p1, p2); cout << "Mid Point(" << p3.getX() << "," << p3.getY() << ")"; return 0; }Output
Mid Point(4,5)
Conclusion
In conclusion, classes and objects in C++ provide a robust foundation for building scalable, maintainable, and reusable software. The advantages of encapsulation, modularity, reusability, and enhanced code organization contribute to the effectiveness of object-oriented programming in creating complex and adaptable systems. By leveraging these features, developers can design more efficient and maintainable code in the C++ programming language.