Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual assignment

Tags:

c++

I'm having some trouble understanding this issue.

I have a class:

class StringProperty { //snipped...
protected:
    std::string s;
public:
    virtual StringProperty& operator= (const std::string &x) {
        s = x;
        return *this;
    }
    virtual StringProperty& foo(const std::string &x) {
        s = x;
        return *this;
    }
};

This class (which have more methods and were snipped for simplicity) should act as a string.

When I derive from it:

class Test : public StringProperty { };

I want to do something like this:

Test x;
x = "test";

However, this fails miserably (does not compile):

error: no match for ‘operator=’ in ‘x = "test"’

Nonetheless, if I use

x.foo("test");

It works. I'm interested in understanding why it fails, since for me both functions are identical.

Thanks.

like image 719
Akobold Avatar asked Feb 24 '26 11:02

Akobold


2 Answers

Your Test class contains an implicitly-declared copy-assignment operator (and also a default constructor, copy constructor and destructor). This hides the one in the base class. In order for that to be considered as an overload, you have to make it accessible in the derived class:

class Test : public StringProperty {
public:
    using StringProperty::operator=;
};
like image 141
Mike Seymour Avatar answered Feb 27 '26 01:02

Mike Seymour


That's classic.

operator= is one of the special methods the compiler creates for you if you don't. Consequently, this automatically created method hides the inherited method.

You can solve it by adding

using StringProperty::operator=;

line to class Test.

like image 43
jpalecek Avatar answered Feb 27 '26 01:02

jpalecek