conceptOfOops
conceptOfOops
represent data and methods to manipulate that data. The core concepts of OOP are designed to
promote code organization, reusability, and scalability. Here are the fundamental concepts of
OOP:
Class: A blueprint for creating objects. It defines attributes (data members) and methods
(functions) that the objects created from the class can use.
cpp
Copy code
class Car {
public:
string model;
int year;
void display() {
cout << "Model: " << model << ", Year: " << year << endl;
}
};
Object: An instance of a class. Objects have state (data) and behavior (methods).
cpp
Copy code
Car myCar;
myCar.model = "Toyota";
myCar.year = 2020;
myCar.display(); // Output: Model: Toyota, Year: 2020
2. Encapsulation
Encapsulation is the concept of bundling the data (attributes) and the methods (functions) that
operate on the data into a single unit (class). It restricts direct access to some components and
can protect the integrity of the object’s state.
Access Modifiers:
o Public: Members can be accessed from outside the class.
o Private: Members can only be accessed from within the class.
o Protected: Members can be accessed within the class and by derived classes.
3. Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only the
necessary features of an object. This simplifies interactions with complex systems and enhances
usability.
cpp
Copy code
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
4. Inheritance
Inheritance allows a new class (derived class) to inherit attributes and methods from an existing
class (base class). This promotes code reuse and establishes a hierarchical relationship.
Types of Inheritance:
o Single Inheritance: One derived class from one base class.
o Multiple Inheritance: One derived class from multiple base classes.
o Multilevel Inheritance: A derived class inherits from another derived class.
o Hierarchical Inheritance: Multiple derived classes inherit from a single base
class.
cpp
Copy code
class Vehicle {
public:
void start() {
cout << "Vehicle started." << endl;
}
};
5. Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon, even
though they share the same name. There are two main types:
cpp
Copy code
void print(int a);
void print(double b);
cpp
Copy code
class Base {
public:
virtual void show() {
cout << "Base class show." << endl;
}
};