Polymorphism or Switch

I am just wondering which is better

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class bird {
public:

float fly_speed(){
	switch( _type ){
	case COLIBRI:
		return age() * 0.3;
		break;
	case EAGLE:
		return age() * 1.2 + genetics( CODE_X ) * 0.1;
		break;
	case OWL:
		return age() * 0.7 - genetics( CODE_X ) * 0.1;
		break;
	}
}

};



or


1
2
3
4
5
6
7
8
9
class colibri : public bird {
public:
	float fly_speed() //overrides the virtual function somewhere
	{
		return age() * 0.3;
	}
};

//and so on 



I admit typing the switch is a lot faster than doing polymorphism
and hypothetically speaking I think the polymorphism is slighlty more efficient

But if it just for slight perfomence difference, than I think I will go with switch cause it safes a lot of time.

But just want to know which is better ?
I think polymorphism is better? Depends on compiler optimizations. If that's a bad optimizer, it will translate the switch with a bunch of if/then/else, otherwise it will be translated as a jumptable (Virtual classes have kinda a jumptable, the vtable)
Last edited on
is TDM GCC 4.7.1 good enough ??
> I admit typing the switch is a lot faster than doing polymorphism

Right now, yes. But if tomorrow you wand to add a couple of more birds, say thrush and wren, (or for that matter some more operations) you might find that a polymorphic hierarchy of birds is easier to maintain.


Either may be better - you need to take a decision based on your expectation of how your program might evolve.
Ok...

Thanx for your answers
I think I will go with polymorphism for now

I think the only thing that bothers my mind is that it's hard to inheritance the contstructor...
Topic archived. No new replies allowed.