Object-Oriented Programming (OOP) in C++
-
Object-Oriented Programming (OOP) is a programming paradigm that focuses on organizing code into objects, which are instances of classes. It emphasizes concepts such as encapsulation, inheritance, and polymorphism to create modular and reusable code.
-
Classes are user-defined data types in C++ that encapsulate data and functions. Objects are instances of classes. Learn how to create classes, define member functions, and access class members using objects.
-
Constructors are special member functions that initialize objects when they are created. Destructors are used to release resources when objects are destroyed. Learn about different types of constructors and destructors in C++.
-
Encapsulation in C++ is defined as the wrapping up of data and information in a single unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulate them.
Two Important property of Encapsulation
- Data Protection - Encapsulation protects the internal state of an object by keeping its data members private. Access to and modification of these data members is restricted to the class’s public methods, ensuring controlled and secure data manipulation.
- Information Hiding - Encapsulation hides the internal implementation details of a class from external code. Only the public interface of the class is accessible, providing abstraction and simplifying the usage of the class while allowing the internal implementation to be modified without impacting external code.
Example
#include <iostream> using namespace std; class temp{ int a; int b; public: int solve(int input){ a=input; b=a/2; return b; } }; int main() { int n; cin>>n; temp half; int ans=half.solve(n); cout<<ans<<endl; }
-
Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.
Types of Abstraction
- Data abstraction – This type only shows the required information about the data and hides the unnecessary data.
- Control Abstraction – This type only shows the required information about the implementation and hides unnecessary information.
Example
// working of Abstraction #include <iostream> using namespace std; class implementAbstraction { private: int a, b; public: // method to set values of // private members void set(int x, int y) { a = x; b = y; } void display() { cout << "a = " << a << endl; cout << "b = " << b << endl; } }; int main() { implementAbstraction obj; obj.set(10, 20); obj.display(); return 0; }
-
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A person at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person possesses different behavior in different situations. This is called polymorphism.
Types of Polymorphism
-
Compile Time Polymorphism – This type of polymorphism is achieved by function
overloading or operator overloading.
-
Function Overloading - When there are multiple functions with the same name but
different parameters, then the functions are said to be overloaded, hence this is known as Function
Overloading. Functions can be overloaded by changing the number of arguments or/and changing the
type of arguments. In simple terms, it is a feature of object-oriented programming providing many
functions that have the same name but distinct parameters when numerous tasks are listed under one
function name. There are certain Rules of Function Overloading that should be followed while
overloading a function.
Example
// C++ program to demonstrate // function overloading or // Compile-time Polymorphism #include <bits/stdc++.h> using namespace std; class Poly { public: // Function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // Function with same name but // 1 double parameter void func(double x) { cout << "value of x is " << x << endl; } // Function with same name and // 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; // Driver code int main() { Poly obj1; // Function being called depends // on the parameters passed // func() is called with int value obj1.func(7); // func() is called with double value obj1.func(9.132); // func() is called with 2 int values obj1.func(85, 64); return 0; }
-
Operator Overloading - C++ has the ability to provide the operators with a special
meaning for a data type, this ability is known as operator overloading. For example, we can make use
of the addition operator (+) for string class to concatenate two strings. We know that the task of
this operator is to add two operands. So a single operator ‘+’, when placed between integer
operands, adds them and when placed between string operands, concatenates them.
// C++ program to demonstrate // Operator Overloading or // Compile-Time Polymorphism #include <iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i = 0) { real = r; imag = i; } // This is automatically called // when '+' is used with between // two Complex objects Complex operator+(Complex const& obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << " + i" << imag << endl; } }; // Driver code int main() { Complex c1(10, 5), c2(2, 4); // An example call to "operator+" Complex c3 = c1 + c2; c3.print(); }
-
Function Overloading - When there are multiple functions with the same name but
different parameters, then the functions are said to be overloaded, hence this is known as Function
Overloading. Functions can be overloaded by changing the number of arguments or/and changing the
type of arguments. In simple terms, it is a feature of object-oriented programming providing many
functions that have the same name but distinct parameters when numerous tasks are listed under one
function name. There are certain Rules of Function Overloading that should be followed while
overloading a function.
-
Runtime Polymorphism – This type only shows
the required information about the implementation and hides
unnecessary information.
-
Function Overriding - Function Overriding occurs when a derived class has a
definition for one of the member functions of the base class. That base function is said to be
overridden.
// C++ program for function overriding with data members #include <bits/stdc++.h> using namespace std; // base class declaration. class Animal { public: string color = "Black"; }; // inheriting Animal class. class Dog : public Animal { public: string color = "Grey"; }; // Driver code int main(void) { Animal d = Dog(); // accessing the field by reference // variable which refers to derived cout << d.color; }
-
Virtual Function - A virtual function is a member function that is declared in the
base class using the keyword virtual and is re-defined (Overridden) in the derived class.
// C++ Program to demonstrate // the Virtual Function #include <iostream> using namespace std; // Declaring a Base class class Base { public: // virtual function virtual void display() { cout << "Called virtual Base Class function" << "\n\n"; } void print() { cout << "Called Base print function" << "\n\n"; } }; // Declaring a Child Class class Child : public Base { public: void display() { cout << "Called Child Display Function" << "\n\n"; } void print() { cout << "Called Child print Function" << "\n\n"; } }; // Driver code int main() { // Create a reference of class GFG_Base Base* base; Child child; base = &child; // This will call the virtual function base->GFG_Base::display(); // this will call the non-virtual function base->print(); }
-
Function Overriding - Function Overriding occurs when a derived class has a
definition for one of the member functions of the base class. That base function is said to be
overridden.
-
Compile Time Polymorphism – This type of polymorphism is achieved by function
overloading or operator overloading.
-
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.
- Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
- Super Class: The class whose properties are inherited by a sub-class is called Base Class or Superclass.
- Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
Example
// Example: define member function without argument within // the class #include <iostream> using namespace std; class Person { int id; char name[100]; public: void set_p() { cout << "Enter the Id:"; cin >> id; cout << "Enter the Name:"; cin >> name; } void display_p() { cout << endl <<"Id: "<< id << "\nName: " << name <<endl; } }; class Student : private Person { char course[50]; int fee; public: void set_s() { set_p(); cout << "Enter the Course Name:"; cin >> course; cout << "Enter the Course Fee:"; cin >> fee; } void display_s() { display_p(); cout <<"Course: "<< course << "\nFee: " << fee << endl; } }; int main() { Student s; s.set_s(); s.display_s(); return 0; }
-
In dynamic binding, the code to be executed in response to the function call is decided at runtime. C++ has virtual functions to support this. Because dynamic binding is flexible, it avoids the drawbacks of static binding, which connected the function call and definition at build time.
Example
// C++ Program to Demonstrate the Concept of Dynamic binding // with the help of virtual function #include <iostream> using namespace std; class Dynamic { public: void call_Function() // function that call print { print(); } void print() // the display function { cout << "Printing the Base class Content" << endl; } }; class Dynamic2 : public Dynamic { public: void print() { cout << "Printing the Derived class Content" << endl; } }; int main() { Dynamic dynamic; // Creating Dynamic object dynamic.call_Function(); // Calling call_Function Dynamic2 dynamic2; // creating Dynamic2 object dynamic2.call_Function(); // calling call_Function // for GFG2 object return 0; }
-
Objects communicate with one another by sending and receiving information. A message for an object is a request for the execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function, and the information to be sent.