Assinging a base object to an inherited object

B

bg_ie

Hi,

Lets say I have an class called Base which is inherited by a class
called Top. Now lets say I want to assign an object of type Base to an
object of type Top, how can I do this so that all the members present
in the Base object are assigned to the corresponding members in the
Top object, with the remaining values set to null?

Thanks for your help,

Barry.
 
V

Victor Bazarov

Lets say I have an class called Base which is inherited by a class
called Top. Now lets say I want to assign an object of type Base to an
object of type Top, how can I do this so that all the members present
in the Base object are assigned to the corresponding members in the
Top object, with the remaining values set to null?

Use a converting constructor

class Top : public Base {
int rest;
public:
Top(Base const& b) : Base(b), rest(0) {}
};

or a custom assignment operator

class Top : public Base {
int rest;
public:
Top& operator =(Base const& b) {
Base::eek:perator=(b);
rest = 0;
return *this;
}
};

V
 
C

Chris Theis

Hi,

Lets say I have an class called Base which is inherited by a class
called Top. Now lets say I want to assign an object of type Base to an
object of type Top, how can I do this so that all the members present
in the Base object are assigned to the corresponding members in the
Top object, with the remaining values set to null?

You could implement a custom assignment op or conversion ctor that takes a
Base object and calls the base class' assignment op after upcasting the this
pointer to base, or calling it explicitely.

Of course you'd have to set the remaining member variables of Top to zero
manually but usually that would be taken care of by the initial constructor
anyway (if there is no reason to set some variables to a predefined state
that is not valid anymore after the assignment of a base object).

Cheers
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top