Wednesday, 15 January 2014

c++ - When is it appropriate to use inheritance? -



c++ - When is it appropriate to use inheritance? -

i've gotten direct responses along lines of "if child-to-be subtype of parent, utilize inheritance." worked while doing little projects, started working on 2d game engine i've run conflicting cases.

let’s have base of operations class gameobject, has, sake of arguments, 50 functions , 5 fellow member variables. functions setters, getters, animation functions, rendering, moving , on. perfect base of operations class player , enemies.

but have objects items , props need (and want able access) 10 of functions inherited gameobject. item can still defined gameobject, doesn't move or have animation.

what here? inherit , ignore functions, creating wasted memory? rewrite 10 functions, wasting time? create gameobject private fellow member variable of item , prop, 1 time 1 time again wasting memory allowing me block access unwanted functions? or remove needed 10 functions gameobject , stick them in separate header creating library of auxiliary functions?

edit:

thanks replies. pretty much either said split gameobject class improve defined base of operations classes or utilize composition.

inheritance needs used carefully. , remember rule - prefer composition on inheritance. not simplify code, create more agile , unit-testable. game class should not serve base of operations class player class. but, may contain player object or vector of them.

keep in mind, have separate functionality. game class should not much aware of the player class. should know public interface. hence here comes concept of interfaces. rather containing vector of player objects, improve contain vector of iplayer interfaces. class player implement iplayer interface. handy because in future might want introduce new type of player, in cause wouldn't have modify game class, neither have modify player class, have new instance superplayer class 1 time 1 time again implement iplayer interface.

there tons of documentation on topic online. here @ to the lowest degree 2 rules of thumb: 1) utilize interfaces wherever can, 2) prefer composition on inheritance.

hope helpful.

c++ inheritance

No comments:

Post a Comment