Sunday, 15 February 2015

c++ - We use inheritance when A (derived class) "is a" B (base class). What do we do when A "can be" B or C? -



c++ - We use inheritance when A (derived class) "is a" B (base class). What do we do when A "can be" B or C? -

sorry ugly question, didn't know how word it. i'll give illustration of mean:

a human can mage or warrior, mage , warrior inherit human. if orc can both too? can't "a human warrior" or "a warrior human". orc , human (or parent class, humanoid) inherit skills, , take use?

i don't know if should tag specific language, since it's general question oop, since different languages can have different approaches same problem, prefer answers c++ perspective.

improve modelling

abstract class race, concrete classes human, orc, etc... abstract class class, concrete classes mage, warrior, etc...

when calculating stats mage, instance, inquire race (not human, or orc) things int get_intelligence_bonus() (abstract function in race). if @ possible, interactions should between race , class, not concrete counterparts.

use composition build character:

character::character( std::unique_ptr<race> r, std::unique_ptr<class> c ) { // calculate stats, etc... }

you can utilize pure oop dynamic binding or if prefer, can utilize templates static-time binding, that's orthogonal implementation issue. either way, need class hierarchy right.

if new c++ or if need race , class in constructor, may utilize const& instead of std::unique_ptr<>. if serious learning c++, read ownership semantics , variable lifetimes can improve understand std::unique_ptr<>.

http://en.cppreference.com/w/cpp/memory/unique_ptr

c++ oop inheritance

No comments:

Post a Comment