Reputation: 849
Let's say I have following code exploiting the dynamic polymorphism in C++
GraphicalObject.h
class GraphicalObject
{
public:
virtual void draw() = 0;
};
Rectangle.h
#include "GraphicalObject.h"
class Rectangle : public GraphicalObject
{
void draw();
};
Rectangle.cpp
#include "Rectangle.h"
#include <iostream>
void Rectangle::draw() {
std::cout << "Drawing rectangle!" << std::endl;
}
Circle.h
#include "GraphicalObject.h"
class Circle : public GraphicalObject
{
void draw();
};
Circle.cpp
#include "Circle.h"
#include <iostream>
void Circle::draw() {
std::cout << "Drawing circle!" << std::endl;
}
main
int main(int argc, char** argv) {
Rectangle rectangle;
Circle circle;
GraphicalObject* picture[2];
picture[0] = &rectangle;
picture[1] = &circle;
for(GraphicalObject* o : picture) {
o->draw();
}
return 0;
}
My question is whether there is a possibility how to have the picture
array
without dynamic polymorphism and instead of use only the static polymorphism and
avoid the virtual method? The reason why I would like to avoid the virtual method is that I would like to avoid the overhead related to the access into the vtable.
Upvotes: 0
Views: 123
Reputation: 14589
The problem here is that objects pointed by GraphicalObject* picture[2];
got static type GraphicalObject
and static polymorphism uses static type.
But that doesn't mean static polymorphism isn't possible is similar situation. You would need a wrapper class which would know the actual type of stored object and would cast the pointer to it before calling the methods.
Upvotes: 1