Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Assinging a base object to an inherited object (http://www.velocityreviews.com/forums/t495876-assinging-a-base-object-to-an-inherited-object.html)

bg_ie@yahoo.com 04-02-2007 02:56 PM

Assinging a base object to an inherited object
 
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.


Victor Bazarov 04-02-2007 03:03 PM

Re: Assinging a base object to an inherited object
 
bg_ie@yahoo.com wrote:
> 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::operator=(b);
rest = 0;
return *this;
}
};

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask



Chris Theis 04-02-2007 03:34 PM

Re: Assinging a base object to an inherited object
 

<bg_ie@yahoo.com> wrote in message
news:1175525783.007537.234190@e65g2000hsc.googlegr oups.com...
> 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




All times are GMT. The time now is 11:07 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.