Table of Contents
ToggleObject-Oriented Programming (OOP) in C++ is a programming paradigm centered around objects that contain data and code. OOP models real-world entities, like customers or orders, as modular, reusable objects to enable more efficient and adaptable software development.
In this article we will look into basic OOPS Concepts in C++.We will also cover basic building blocks like classes, objects, encapsulation, inheritance, polymorphism, abstraction and dynamic binding.So, let’s get started.
What is OOPS in C++?
Object-Oriented Programming (OOP) in C++ is a programming paradigm that emphasises the use of objects and classes as the fundamental building blocks of a program, focusing on the encapsulation of data and behaviours rather than prioritising actions and data as separate entities.This approach differs fundamentally from traditional procedural programming.
OOPS in C++ is significant for several reasons:
- Modularity: It allows for dividing a complex problem into smaller, manageable units (classes and objects).
- Reusability: Through inheritance, classes can be reused to create new classes, saving time and reducing errors.
- Flexibility: Polymorphism enables a single function to adapt to different contexts, enhancing flexibility in code.
- Maintainability: With encapsulation, code is more organized, and changes in one part of the system have minimal impact on other parts.
Example: Basic Class and Object
// OOPS Concepts in C++: Class and Object
#include <iostream>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
void displayInfo() {
cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << endl;
}
};
int main() {
Car car1;
car1.brand = "Toyota";
car1.model = "Corolla";
car1.year = 2021;
car1.displayInfo();
return 0;
}
In this example, Car
is a class with attributes (brand, model, year) and a method displayInfo()
. An object car1
is created from the Car
class and its attributes are set and displayed.
Comparison with Procedural Programming
Procedural programming, a different paradigm, is based on the concept of procedure calls. It is a step-by-step approach to programming where data is separate from functions. The primary focus is on functions rather than the flow of data.
Example: Procedural Approach
#include <iostream>
using namespace std;
struct Car {
string brand;
string model;
int year;
};
void displayCarInfo(Car car) {
cout << "Brand: " << car.brand << ", Model: " << car.model << ", Year: " << car.year << endl;
}
int main() {
Car car1 = {"Toyota", "Corolla", 2021};
displayCarInfo(car1);
return 0;
}
In this procedural example, Car
is a simple structure, and displayCarInfo
is a function that operates on this structure. Unlike OOP, there’s no encapsulation of data and functions.
Procedural Programming Vs OOPS In C++
- Encapsulation: OOP encapsulates data and functions into classes and objects, whereas procedural programming treats data and functions as separate entities.
- Focus: OOP focuses on objects and their interactions, while procedural programming focuses on functions and logic sequence.
- Maintenance: OOP is generally more maintainable and scalable, making it suitable for large, complex applications.
Features and Characteristics of OOPS in C++
Key features and characteristics of OOPS in C++ are
- Classes and Objects
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
- Dynamic Binding
Let’s discuss each of these concepts of OOPS in C++ in detail.
Basic OOPS Concepts in C++
Basic OOPS Concepts in C++ are:
Class
A class in C++ is a blueprint for creating objects. It encapsulates data for the object and methods that operate on that data.
Structure of a Class
// OOPS Concepts in C++: Class
class ClassName {
// Access specifier
private:
// Data Members
public:
// Member Functions()
};
Example
class Rectangle {
private:
int width, height;
public:
void setValues(int x, int y) {
width = x;
height = y;
}
int area() {
return width * height;
}
};
In this example, Rectangle
is a class with private data members width
and height
, and public functions setValues
and area
.
Object
An object is an instance of a class. When a class is defined, no memory is allocated until an object is instantiated.
Instantiating an Object
// OOPS Concepts in C++: Object
Rectangle rect;
rect.setValues(5, 6);
cout << "Area: " << rect.area();
Here, rect
is an object of the Rectangle
class, and we are calling its methods.
Encapsulation
Encapsulation is the bundling of data and methods that operate on the data within one unit, or class, keeping both safe from outside interference and misuse.
Access Specifiers
Access Specifier | Within Class | Within same assembly | Derived Class (same assembly) | Derived Class (other assembly) | Outside Class |
---|---|---|---|---|---|
Private | Yes | No | No | No | No |
Protected | Yes | Yes | Yes | No | No |
Public | Yes | Yes | Yes | Yes | Yes |
Default (no specifier) | Yes | Yes | Yes | No | No |
- Private members are accessible only within the same class
- Protected are accessible within the same class and derived classes in the same assembly
- Public members are accessible from anywhere
- Default access is private to the assembly
Example of Encapsulation
// OOPS Concepts in C++: Encapsulation
class EncapsulatedObject {
private:
int hiddenData;
public:
void setData(int data) {
hiddenData = data;
}
int getData() {
return hiddenData;
}
};
In this example, hiddenData
is a private member, accessible only through public functions setData
and getData
.
Abstraction
Abstraction is the concept of hiding the complex reality while exposing only the necessary parts. It’s more about creating a simple interface to the outside world.
Abstract Classes
An abstract class is a class that cannot be instantiated and is typically used to define an interface.
Example:
class AbstractClass {
public:
virtual void aVirtualFunction() = 0; // Pure virtual function makes this class Abstract
};
class ConcreteClass : public AbstractClass {
public:
void aVirtualFunction() {
cout << "Implemented Virtual Function";
}
};
Here, AbstractClass
is an abstract class because it contains at least one pure virtual function. ConcreteClass
is a subclass that implements the abstract method.
Interfaces
In C++, an interface is a class where all methods are pure virtual functions. It provides a contract for the classes that inherit it.
Example of an Interface
class ShapeInterface {
public:
virtual void draw() = 0; // Pure virtual function
virtual void move() = 0; // Pure virtual function
};
class Circle : public ShapeInterface {
public:
void draw() override {
cout << "Drawing Circle" << endl;
}
void move() override {
cout << "Moving Circle" << endl;
}
};
class Rectangle : public ShapeInterface {
public:
void draw() override {
cout << "Drawing Rectangle" << endl;
}
void move() override {
cout << "Moving Rectangle" << endl;
}
};
In this example, ShapeInterface
is an interface with pure virtual functions draw
and move
. Circle
and Rectangle
are concrete classes implementing this interface. This ensures that any shape class derived from ShapeInterface
must implement the draw
and move
methods.
Inheritance
Inheritance is a mechanism in C++ where a new class is derived from an existing class. The derived class inherits attributes and methods of the base class. Key benefits include code reusability, method overriding, and the ability to create polymorphic classes.
Types of Inheritance
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Type | Description |
---|---|
Single Inheritance | Inheritance in which a derived class is inherited from only one base class. This allows reuse of the base class code in the derived class. |
Multiple Inheritance | Inheritance in which a derived class inherits features from multiple base classes. This allows reuse of multiple base classes. |
Multilevel Inheritance | Type of inheritance in which a derived class is inherited from another derived class. This allows reuse of existing derived classes. |
Hierarchical Inheritance | Inheritance type in which multiple classes inherit from the same base class. Allows extensive reuse of common base class code. |
Hybrid Inheritance | Refers to inheritance involving multiple types of inheritance forms. For example using multiple inheritance and multilevel inheritance together. |
Example: Single Inheritance
// OOPS Concepts in C++: Inheritance
class Animal { // Base class
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal { // Derived class
public:
void bark() {
cout << "Barking..." << endl;
}
};
// Usage
Dog d;
d.eat(); // Inherited
d.bark(); // Own function
Polymorphism
Polymorphism in object-oriented programming refers to the ability of objects or functions to take on multiple forms, allowing them to behave differently based on the context or the specific class they belong to. It enables code to work with objects in a flexible and dynamic manner, promoting code reusability and abstraction.
Types of Polymorphism
- Compile-Time Polymorphism: Achieved by function and operator overloading.
- Runtime Polymorphism: Achieved by function overriding, using virtual functions.
Example of Method Overloading (Compile-Time Polymorphism)
// OOPS Concepts in C++: Polymorphism
class Print {
public:
void show(int i) {
cout << "Integer: " << i << endl;
}
void show(double f) {
cout << "Double: " << f << endl;
}
};
// Usage
Print p;
p.show(5); // Calls integer version
p.show(5.5); // Calls double version
Int he above code two show
methods with different parameter types (int and double) allow the compiler to select the appropriate method based on the argument’s data type when calling p.show()
, resulting in Compile-Time Polymorphism.
Example of Method Overriding (Runtime Polymorphism)
// OOPS Concepts in C++: Polymorphism
class Base {
public:
virtual void print() {
cout << "Base function" << endl;
}
};
class Derived : public Base {
public:
void print() override {
cout << "Derived function" << endl;
}
};
// Usage
Base *bptr;
Derived d;
bptr = &d;
bptr->print(); // Calls Derived's print()
In the above code the print
method in the Derived
class overrides the one in the Base
class, and when a Derived
object is assigned to a Base
pointer and the print
method is called via the pointer (bptr->print()
), it dynamically resolves to the Derived
class’s print
method at runtime, resulting in “Derived function” being printed.
Dynamic Binding
Dynamic binding refers to the linking of a procedure call to the code to be executed in response to the call at runtime. It’s fundamental to runtime polymorphism in OOP.
Implementation in C++
Dynamic binding in C++ is achieved through virtual functions and pointers. A virtual function in a base class specifies that the function is intended to be overridden in derived classes.
Example
// OOPS Concepts in C++: Dynamic Binding
class Base {
public:
virtual void show() {
cout << "Base show" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived show" << endl;
}
};
// Usage
Base *bptr;
Derived d;
bptr = &d;
bptr->show(); // Calls Derived's show()
In this example, the virtual function show
is defined in the base class and overridden in the derived class. The type of object pointed to by bptr
determines which show
function is called, showcasing dynamic binding.
Key TakeAways
- OOP focuses on bundling data and functions into objects, unlike procedural programming which separates data and functions. This provides modularity, maintainability and code reuse.
- Basic concepts of OOPS In C++ are classes, objects, encapsulation, inheritance, polymorphism, abstraction and dynamic binding.
- Encapsulation bundles data and functions into a class, restricting access using access specifiers like private and public.
- Inheritance allows creating new classes from existing ones, enabling code reuse. C++ supports different types like single, multiple, multilevel etc.
- Polymorphism allows the same function name to behave differently based on object type. Method overloading and overriding are examples.
- Dynamic binding or late binding determines which function to call at runtime based on object type, enabling polymorphism.
- OOP makes code modular, maintainable and reusable through encapsulation and inheritance. Polymorphism and dynamic binding provide flexibility.
Also Check,
I hope You liked the post 👍. For more such posts, 📫 subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.
FAQ
What is the basic concept of C++?
C++ is a high-level programming language that combines the features of both procedural and object-oriented programming. It is known for its efficiency and control over system resources, often used in software development for system/application software, drivers, and client-server applications.
Is C++ an OOP?
Yes, C++ is an object-oriented programming (OOP) language. It supports OOP concepts such as classes, inheritance, polymorphism, and encapsulation, allowing for the creation of complex applications with reusable and maintainable code