c++ - Getting OOP right -
ok, problem. have following classes:
class job { bool iscomplete() {} void setcomplete() {} //other functions }; class songjob: public job { vector<job> v; string getartist() {} void setartist() {} void addtrack() {} string gettrack() {} // other functions }; // implemeted
now want implement videojob , derived job. here problem. have following function witch set work songjob:
void process(songjob s) { // not real functions s.setartist(); .............. s.getartist(); ............. s.getartist(); ............... s.setartist() }
here want show function uses derived object methods. if have object derived job, need change parameter job, compiler not know thoose functions , dont test kind of object , cast can call correct function.
so okay put functions in base class, because have no problem, don't know if correct oop, if 1 class deals songs , other videos, thing oop means have 2 clases.
if didn't make myself clear, please , try explaining better.
, in short words, want use polymorfism.
it totally fine put things classes songjob
, videojob
have in common common base-class. however, cause problems once want add subclass of job
has nothing artists.
there things note code have posted. first, class job
apparently not abstract base class. means can have jobs jobs. not songjob
, not videojob
. if want make clear there can not simple job
, make base-class abstract:
class job { virtual bool iscomplete() = 0; virtual void setcomplete() = 0; //other functions };
now, cannot create instances of job
:
job job; // compiler-error std::vector<job> jobs; // compiler-error
note functions virtual, means subclasses can override them. = 0
, end means subclasses have provide implementation of these functions (they pure virtual member functions).
secondly, class songjob
has member std::vector<job>
. not want. if add songjob
vector, become normal job
. effect called slicing. prevent it, you'd have make std::vector<job*>
.
there more here, go far. suggest book.
Comments
Post a Comment