c++ - How can I pass pointer-pointers of a derived class as a based class? -
this follow-up the question asked earlier.
lib_a
i have base class in external library, say, lib_a.
class instrument { // ... } lib_b
i have derived class in external library, say, lib_b, of course references lib_a.
class bond : public instrument { // ... }; in lib_b, have trader class owns pointer bond it's working with.
class trader { public: // ... bond* _bond; }; lib_c
i cannot touch lib_a or lib_b.
in own code, third "library" (i'm using term loosely here), say, lib_c, i'm trying create class points trader's bond pointer, i.e.
class tradehelper { public: tradehelper(bond** bondptr): _bondptr(bondptr) {} bond** _bondptr; }; with being constructed by
trader* t; // assume given , not null tradehelper* th = new tradehelper(&(t->_bond)) an aside (no need read)
why such convoluted scheme? well, trader::_bond can change, , tradehelper needs know trader's _bond is, @ times. essentially, tradehelper gets linked trader. why, if had freedom things my way, have done described—linked 2 this:
class tradehelper { public: tradehelper(trader* t): _trader(t) {} trader* _trader; }; with being constructed by
trader* t; // assume given , not null tradehelper* th = new tradehelper(t); and referred bond via _trader->_bond.
alas, reasons of history , just-the-way-things-are, thing have available me constructing tradehelper pointer trader::_bond, not trader itself. hence use of double-pointer.
the problem
well, everything, described, work fine. real problem lib_c cannot reference lib_b, lib_a. means tradehelper cannot know bond, instrument. example rewritten, looks this:
class tradehelper { public: tradehelper(instrument** instptr): _instptr(instptr) {} instrument** _instptr; }; and therein lies problem, when construct it:
tradehelper* th = new tradehelper(&(t->_bond)); as learned in this question, there no implicit conversion bond** instrument**.
i guess abstract question similar 1 asked previously: how can pass pointer-to-a-derived-class-pointer pointer-to-a-base-class-pointer, given allowed assume pointers used safely? in previous question sought doing wrong, , having learned, felt needed describe situation in more detail able suggest way forward.
reworded, want object x know "where" object y's member is, member derived class, , object x knows base class.
i've tinkered pointer references , casting can't seem figure way out.
i've reconstructed example using dynamic_cast , had no problems constructing tradehelper way. there reason can't use dynamic_cast in code?
trader trader; bond b; trader._bond = &b; trader* t = &trader; instrument* inst = dynamic_cast<instrument*>(t->_bond); if (inst == null) { std::cout << "dynamic_cast failed!" << std::endl; return 1; } tradehelper* th = new tradehelper(&inst); delete th;
Comments
Post a Comment