No, you don't have to use polymorphism just because you're using inheritance. Inheritance and polymorphism are related but distinct concepts in C++.
Inheritance, by itself, provides several key benefits:
GreenRectangle
) automatically inherits the members (data and functions) of its base class (Rectangle
). You only need to write code for what's new or different in the derived class.GreenRectangle
is a Rectangle
. This reflects a logical relationship between the classes.You can use inheritance purely for these reasons without ever needing polymorphism. For example, if you simply wanted a GreenRectangle
type that always started green, you could use it directly:
// GreenRectangle.h
#pragma once
#include "Rectangle.h"
class GreenRectangle : public Rectangle {
public:
GreenRectangle(const SDL_Rect& Rect)
: Rectangle{Rect} {
// Set specific properties after base
// class construction
SetColor({0, 255, 0});
SetHoverColor({0, 150, 0}); // Maybe a darker green
}
// Can add specific GreenRectangle methods here
};
// main.cpp (Conceptual Example)
#include "GreenRectangle.h"
#include <vector>
// ...
int main(int argc, char** argv) {
// ...
GreenRectangle SpecialRect{SDL_Rect{10, 10, 50, 50}};
std::vector<GreenRectangle> GreenRects;
GreenRects.emplace_back(SDL_Rect{70, 10, 50, 50});
GreenRects.emplace_back(SDL_Rect{130, 10, 50, 50});
// ...
}
In this scenario, we are using GreenRectangle
and maybe even storing it in a vector of GreenRectangle
, but we aren't treating it polymorphically through a Rectangle*
or Rectangle&
.
Polymorphism becomes essential when you want to treat objects of different derived types uniformly through a pointer or reference to their common base class.
This is exactly what we did in the lesson when we created a std::vector<std::unique_ptr<Rectangle>>
. This vector could hold pointers to both Rectangle
objects and GreenRectangle
objects. When we iterated through the vector and called ptr->Render(Surface)
, polymorphism (enabled by the virtual
keyword, discussed elsewhere) ensures the correct Render
function (either the base Rectangle
version or the derived GreenRectangle
version) gets called based on the actual type of object the pointer points to at runtime.
So, use inheritance alone for code reuse and specialization. Add polymorphism (using virtual
functions and base class pointers/references) when you need to manage and operate on collections of related but distinct object types through a common interface.
Answers to questions are automatically generated and may not have been reviewed.
Discover how to organize SDL components using manager classes, inheritance, and polymorphism for cleaner code.