c++ - How to implement clone in a pure abstract class? -
so want override pure abstract method in derived classes got error. can help me see happened , how can finish it.
my device
class;
class device { public: device(); device(const device& orig); virtual ~device(); virtual device clone() = 0; }
and derived class;
class radar : public device { public: radar(); // radar(const radar& orig); // commenting compiler using default re-create constructor virtual ~radar(); radar clone(); };
source file radar
class;
radar radar::clone() { homecoming *(new radar(*this)); }
if utilize device
type in clone
method in device
class, pop-up device
abstract class.
if utilize void
type (which i'm assuming it's not want have), show haven't implement method.
what should do?
your clone
method need homecoming pointers cloned objects... covariant homecoming types work way (as returning value asking caller re-create returned value stack - memory leak when you've allocated new
).
so, should be:
virtual device* clone() = 0;
...and later...
radar* clone(); // yes, should radar* here - uses c++'s back upwards // "covariant homecoming types", see "update" give-and-take radar* radar::clone() { homecoming new radar(*this); }
update - farther explanation requested
so, thought clone function can homecoming deep re-create of whatever actual derived type device*
addressing. given derived type might add together info members device
lacked, larger object, , caller has no ability reserve right amount of stack space in store it. reason, object needs allocated dynamically new
, , predictably-sized device*
caller's way access new object. it's legal clone function homecoming radar*
though - means client code knows @ compile time dealing radar
, clones can go on utilize radar
- accessing members radar
provides.
hope helps clarify things. might want background reading on object oriented programming.
c++ abstract derived-class
No comments:
Post a Comment