PDA

View Full Version : What is best inheritate or use methods of public object ?



tonnot
24th February 2012, 10:34
I have a doubt.
I can have a class A that inheritates another B, so I can use methods of B.
But I could have a public B object creates inside A, in this case I could use B-methods also.

What is best ? What is fast to compile ? What is fast to run ?
Thanks.

Zlatomir
24th February 2012, 12:36
You use inheritance if A is somehow an extended B: a simple example is a class Car and Engine: a Car instance has an Engine and it's not logical that Car derives from Engine (even if Car functionality needs the Engine), but an My_Custom_Designed_Car could derive from Car (and can use the public functionality of a Car just like if it is a Car including some functionality that start movement (using the engine ;) ).

So if A is an B and it makes sense that A is used like*** an B use inheritance. ***including the polymorphic (virtual) member-function calls

LE: switched the A and B (i first read class B : public A instead of what you said class A : public B - code makes it simpler)

amleto
25th February 2012, 17:15
prefer composition over inheritance where the aim is just code re-use.

Write your code with readability and maintenance in mind, NOT speed of compiling or running.