Polymorphism - run-time vs. compile-time

S

Samee Zahur

Hello,
The other day I was rather shocked to find that I couldn't find
a good use for runtime polymorphism! Let me explain this a bit further
before you get shocked. Any function that I could previously write like
this:
void func1(Base& obj)
{
//...
obj.virmeth(); //Call virtual method
//...
}

Is now better written as this for most cases:
template <class T> void func1(T& obj)
{
//...
obj.virmeth(); //Call any method
//...
}

That way, I'll never incurr run-time overheads. Obviously, this
wouldn't
work if I'm trying to separate implementation from use, but this
question hit me so suddenly, that I really couldn't find a good answer
then. Now I figured out two situations where this isn't possible: when
return type must be polymorphic (or is that also used in automatic
template specialization?) ... or when catching exceptions. But I'd
still like to shake myself off this uneasy feeling by hearing a bit
more over which is more suitable when - and even in the cases I
mentioned, I'd like a little discussionW (exceptional cases etc.)

Samee
 
J

Jerry Coffin

Samee said:
Hello,
The other day I was rather shocked to find that I couldn't find
a good use for runtime polymorphism! Let me explain this a bit
further before you get shocked. Any function that I could
previously write like this:

[ virtual function ]
Is now better written as this for most cases:

[ template invocation ]
That way, I'll never incurr run-time overheads. Obviously, this
wouldn't
work if I'm trying to separate implementation from use, but this
question hit me so suddenly, that I really couldn't find a good
answer then. Now I figured out two situations where this isn't
possible: when return type must be polymorphic (or is that also
used in automatic template specialization?) ... or when catching
exceptions. But I'd still like to shake myself off this uneasy
feeling by hearing a bit more over which is more suitable when -
and even in the cases I mentioned, I'd like a little discussionW
(exceptional cases etc.)

The other obvious case would be when you're calling the same virtual
function for all the objects in a collection:

struct shape { virtual void draw() = 0; };
struct square : shape;
struct circle : shape;
// ...

std::vector <shape *> shapes;

// ...

for (int i=0; i<shapes.size(); i++)
shapes->draw();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top