Object-Oriented Programming (OOP) is a paradigm that allows you to model real-world entities as objects with attributes (data) and methods (functions). C++ is a powerful object-oriented language that supports features like classes, inheritance, polymorphism, and encapsulation.
A class is a blueprint for creating objects. It defines the attributes and methods that objects of the class will have.
Example of a class declaration:
class Car {
public:
// Attributes
std::string brand;
int year;
// Method
void drive() {
std::cout << "Driving the " << brand << std::endl;
}
};
In this example, we define a `Car` class with attributes `brand` and `year`, and a method `drive` to simulate driving the car.
An object is an instance of a class. It represents a specific entity with its own unique data and behavior.
Example of creating and using objects:
int main() {
// Creating objects
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2022;
// Using object's methods
myCar.drive();
return 0;
}
In this example, we create a `Car` object named `myCar` and set its attributes. We then call the `drive` method to simulate driving the car.
Inheritance is a mechanism that allows a class to inherit properties and behavior from another class. It promotes code reusability and enables the creation of hierarchical relationships between classes.
Example of class inheritance:
class ElectricCar : public Car {
public:
// Additional attributes
int batteryCapacity;
// Additional method
void charge() {
std::cout << "Charging the electric car" << std::endl;
}
};
In this example, `ElectricCar` is a subclass of `Car`. It inherits the attributes and methods of `Car` and adds its own attributes and methods.
Polymorphism allows objects of different classes to be treated uniformly. It enables flexibility and extensibility in object-oriented systems.
Example of polymorphism using virtual functions:
class Animal {
public:
virtual void makeSound() {
std::cout << "Some generic sound" << std::endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
std::cout << "Woof!" << std::endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
std::cout << "Meow!" << std::endl;
}
};
In this example, `Animal` is a base class with a virtual method `makeSound()`. `Dog` and `Cat` are subclasses that override the `makeSound()` method to produce specific sounds.