Intern
Name the main principles of object-oriented programming.
sobes.tech AI
Answer from AI
Principles of OOP:
- Encapsulation: Combining data (attributes) and methods (functions) that work with this data into a single entity - a class. Hiding the internal implementation of an object from the outside world.
- Inheritance: Creating a new class (derived) based on an existing one (base), inheriting its properties and behavior. Allows code reuse and the creation of class hierarchies.
- Polymorphism: The ability of objects of different classes to respond to the same message (method call) differently, depending on their type. Ensures flexibility and extensibility of code. It is an application of the single responsibility principle — a single method call when working under different implementations.
- Abstraction: Highlighting the essential characteristics of an object and ignoring non-essential details. Creating a simplified model of an object for ease of work.
Example of polymorphism in C++ using virtual functions:
// Base class
class Shape {
public:
// Virtual function
virtual void draw() {
// Base implementation (can be empty or contain common logic)
}
// Destructor should be virtual if the class is used as a base part of the hierarchy
virtual ~Shape() = default;
};
// Derived class
class Circle : public Shape {
public:
void draw() override {
// Implementation for a circle
// std::cout << "Drawing a circle" << std::endl;
}
};
// Derived class
class Square : public Shape {
public:
void draw() override {
// Implementation for a square
// std::cout << "Drawing a square" << std::endl;
}
};
// Function using polymorphism
void drawShape(Shape* shape) {
shape->draw(); // Calls the specific implementation of draw() depending on the object type
}
// In main or another place:
// Circle circle;
// Square square;
// drawShape(&circle); // Calls Circle::draw()
// drawShape(&square); // Calls Square::draw()