dervived class assignment operator

C

Christopher

My derived class assignment operator is not working. It never seems to
get the assignment done. I suspect I am not allowed to implement it
this way, but I am unsure why. Can someone explain what is happening
here?

---------------------------------------------------------
struct Base
{
Base & operator = (const Base & rhs);

int m_x;
};

struct Derived : public Base
{
Derived & operator = (const Derived & rhs);
};

-----------------------------------------------------------
Base & Base::eek:perator = (const Base & rhs)
{
m_x = rhs.m_x;
}

Derived & Derived::eek:perator = (const Derived & rhs)
{
static_cast<Base>(*this) = static_cast<Base>(rhs);

return *this;
}


I did this, because, currently, derived does not have any extra member
data when compared to base.
When it does, I thought I could handle them one by one after the
static cast / base assignment I did above.
I must be wrong?
 
K

Kai-Uwe Bux

Christopher said:
My derived class assignment operator is not working. It never seems to
get the assignment done. I suspect I am not allowed to implement it
this way, but I am unsure why. Can someone explain what is happening
here?

---------------------------------------------------------
struct Base
{
Base & operator = (const Base & rhs);

int m_x;
};

struct Derived : public Base
{
Derived & operator = (const Derived & rhs);
};

-----------------------------------------------------------
Base & Base::eek:perator = (const Base & rhs)
{
m_x = rhs.m_x;
}

Derived & Derived::eek:perator = (const Derived & rhs)
{
static_cast<Base>(*this) = static_cast<Base>(rhs);

On the left hand side, you create a temporary Base object. To that
temporary, something is assigned. This compiles, because the assignment
operator is a member function.

The following should work, but looks awful:

static_cast said:
return *this;
}


I did this, because, currently, derived does not have any extra member
data when compared to base.
When it does, I thought I could handle them one by one after the
static cast / base assignment I did above.
I must be wrong?

No. But you might want to avoid casts:

Derived & Derived::eek:perator = (const Derived & rhs) {
Base::eek:perator= ( rhs );
// other bases
// more members
return ( *this );
}

Best

Kai-Uwe Bux
 

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,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top