C
Corey Cooper
I have a class for which I needed to create an operator= function. I then
use that as a base class for another class, which also needs an operator=.
What is the syntax to use in the derived class operator= function to copy
the base classes variables in the derived class (without just copying the
code?)
A much simplified example:
class Base
{
public:
Base();
~Base();
Base &operator=(const Base &B);
protected:
int i;
}
Base &Base:perator=(const Base &B)
{
if (this == &B)
return *this;
i = B.i;
return *this;
};
class Derived : public Base
{
Derived();
~Derived();
Derived &operator=(const Derived &D);
protected:
int n;
};
Derived &Derived:perator=(const Derived &B)
{
if (this == &B)
return *this;
// None of these work!
//(Base)(*this) = :perator=B;
//(*this) =(const Base &)B;
n = B.n;
return *this;
};
And yet, in code not directly in these classes, this works fine:
Base b;
Derived d;
d = b;
Thanks!
Corey
use that as a base class for another class, which also needs an operator=.
What is the syntax to use in the derived class operator= function to copy
the base classes variables in the derived class (without just copying the
code?)
A much simplified example:
class Base
{
public:
Base();
~Base();
Base &operator=(const Base &B);
protected:
int i;
}
Base &Base:perator=(const Base &B)
{
if (this == &B)
return *this;
i = B.i;
return *this;
};
class Derived : public Base
{
Derived();
~Derived();
Derived &operator=(const Derived &D);
protected:
int n;
};
Derived &Derived:perator=(const Derived &B)
{
if (this == &B)
return *this;
// None of these work!
//(Base)(*this) = :perator=B;
//(*this) =(const Base &)B;
n = B.n;
return *this;
};
And yet, in code not directly in these classes, this works fine:
Base b;
Derived d;
d = b;
Thanks!
Corey