Reputation: 1840
I am overloading operator=
on a struct EqualTestBase
, and operator=
takes different parameters than are used to construct the struct.
struct EqualTestBase
{
EqualTestBase(int one) {}
EqualTestBase& operator=(std::string two)
{
//stuff
return *this;
}
};
It works fine on the base class. But a trival struct derived from it, EqualTestDerived
, acts like it doesn't have the operator=
member function.
struct EqualTestDerived : public EqualTestBase
{
EqualTestDerived(int one) : EqualTestBase(one) {}
};
void test()
{
EqualTestBase basetest(0);
basetest = "test"; //this is fine, compiles
EqualTestDerived derivedtest(0);
derivedtest = "test"; //this does not compile, says there is no constructor that takes type const char[5]
}
Do I have to redefine operator=
on all derived structs, or is there a way to automatically pass down that functionality?
Upvotes: 0
Views: 51
Reputation: 490338
operator=
isn't inherited. If a class doesn't define operator=
itself, the compiler will synthesize one for it (regardless of the fact that its base class does define an operator=
).
If you want something that can be inherited (and can be virtual) you generally want to define it as a function with a different name. The generally accepted name for such a function is clone
(though clone is normally more like a copy constructor, creating a new instance of an object, not just assigning to an existing one).
Upvotes: 2
Reputation: 254621
The derived class has an implicitly-declared copy-assignment operator, which hides the one declared in the base class. You can use using
to bring it into scope:
struct EqualTestDerived : public EqualTestBase
{
EqualTestDerived(int one) : EqualTestBase(one) {}
using EqualTestBase::operator=;
};
Upvotes: 5