c++ inheritance pointer -



c++ inheritance pointer -

it's pretty diffecult me describe problem. have 2 classes, base_a , derived_a. can see names, class derived_a derived base_a. in programme have other 2 classes base_b , derived_b (also inheritance). class base_a contains object of base_b, , class derived_a contains object of derived_b.

class base_a { public: base_a() {} virtual ~base_a() {} base_b b_; base_b* pointer_; void init() { b_ = base_b(); pointer_ = &b_; pointer_->setvalue(1); } void print() { pointer_->getvalue(); } }; class derived_a: public base_a { public: derived_a() {} virtual ~derived_a() {} derived_b b_; derived_b* pointer_; void init() { b_ = derived_b(); pointer_ = &b_; pointer_->setvalue(2); pointer_->increasevalue(); } }; class base_b { public: base_b() {} virtual ~base_b() {} int value_; void setvalue(int value) { value_ = value; } void getvalue() { cout << "base_b: " << value_ << endl; } }; class derived_b: public base_b { public: derived_b() {} virtual ~derived_b() {} void increasevalue() { value_++; } }; int main() { derived_a derived_a = derived_a(); derived_a.init(); derived_a.print(); homecoming 0; }

how can see every class of has 1 object of class b , pointer object. problem is, when phone call function print(), not take derived_b* pointer_, seek access base_b* pointer_, not exist. how can in program, should take pointer according class? or need declarate base_b* pointer_ within derived_a class like:

base::pointer_ = pointer_;

maybe there other method or algorithm problem?

thank lot.

"but seek access base_b* pointer_, not exist"

if deriveda not initialise basea, deriveda not meet "isa" rule inheritance , design needs changed. on face of things:

don't re-use names in derived class such b_, pointer_. confusing , gain no value. make init() virtual. have deriveda::init() phone call basea::init() explicitly. make pointer_ virtual method.

note utilize of "covariant homecoming types" virtual methods.

class basea { public: virtual baseb* pointer() { homecoming &b_; } // etc. }; class deriveda : public basea { public: virtual derivedb* pointer() { homecoming &b_; } // etc. };

c++ inheritance pointers

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -