Object Oriented programming (OOP) is a programming
paradigm that relies on the concept of classes and objects.
It is used to structure a software program into simple, reusable pieces of code blueprints (usually called classes),
which are used to create individual instances of objects.
One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer
to its base class. Polymorphism is the art of taking
advantage of this simple but powerful and versatile feature.
classtriangle:publicshape{public:// Reuse base class constructorsusingshape::shape;// Default destructor~triangle()override=default;// Override area member functiondoublearea()override{returnthis->_side1*this->_side2/2;}};
1 2 3 4 5 6 7 8 91011
classsquare:publicshape{public:// Reuse base class constructorsusingshape::shape;// Default destructor~square()override=default;// Override area member functiondoublearea()override{returnthis->_side1*this->_side2;}};
for(std::unique_ptr<shape>&item:v){if(dynamic_cast<triangle*>(item.get())){std::cout<<"This shape is a triangle\n";}elseif(dynamic_cast<square*>(item.get())){std::cout<<"This shape is a square\n";}elseif(dynamic_cast<shape*>(item.get())){std::cout<<"This is an abstract shape\n";}if(item&&*item==*p){std::cout<<"It has the same area as p: "<<item->area()<<'\n';}}