Concept Flow - OOP principles overview
Start
Encapsulation
Inheritance
Polymorphism
Abstraction
End
This flow shows the four main OOP principles in order: Encapsulation, Inheritance, Polymorphism, and Abstraction.
#include <iostream> class Animal { public: virtual void sound() { } }; class Dog : public Animal { public: void sound() override { std::cout << "Woof"; } };
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create Animal object | Animal a; | Object a created |
| 2 | Call a.sound() | a.sound(); | No output (empty method) |
| 3 | Create Dog object | Dog d; | Object d created |
| 4 | Call d.sound() | d.sound(); | Outputs: Woof |
| 5 | Assign Dog to Animal pointer | Animal* ptr = &d; | Pointer ptr points to Dog object |
| 6 | Call ptr->sound() | ptr->sound(); | Outputs: Woof (polymorphism) |
| 7 | End | Execution stops |
| Variable | Start | After Step 1 | After Step 3 | After Step 5 | Final |
|---|---|---|---|---|---|
| a | none | Animal object | Animal object | Animal object | Animal object |
| d | none | none | Dog object | Dog object | Dog object |
| ptr | none | none | none | Points to Dog object | Points to Dog object |
OOP Principles Overview in C++: - Encapsulation: Bundle data and methods in classes - Inheritance: Derive new classes from existing ones - Polymorphism: Use virtual functions to override behavior - Abstraction: Hide complex details behind simple interfaces Use virtual keyword for polymorphism.
class.struct defines a structure, object is not a keyword, and define is for macros.class to define classes [OK]class Animal {
public:
void sound() { std::cout << "Animal sound"; }
};
class Dog : public Animal {
public:
void sound() { std::cout << "Bark"; }
};
int main() {
Animal* a = new Dog();
a->sound();
delete a;
return 0;
}sound method is not virtual, so the pointer type Animal* calls Animal's method.sound is not virtual, Animal sound is printed.class Vehicle {
private:
int speed;
public:
void setSpeed(int s) { speed = s; }
};
int main() {
Vehicle v;
v.speed = 100;
return 0;
}speed is private and cannot be accessed directly outside the class.v.speed = 100; causes an access violation error.Shape defines a method area() but each derived class calculates area differently. Which OOP principle does this best demonstrate?area() differently, but shares the same interface.Pass the test and this pattern moves unknown