Click here to Skip to main content
15,867,921 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a situation that makes me think that "operator =" is not being inherited, but perhaps I fail to understand the standard. Here is a minimal example that illustrates the problem:
C++
struct Foo {
    Foo &operator =(double const val);
};

struct Bar : public Foo { };

int main(int const argc, char const *const argv[]) {
    Bar a;
    Foo b(a);

    b = 4.5; // No issue
    a = 4.5; // error C2679: binary '=' : no operator found which takes a right-hand
             // operand of type 'double' (or there is no acceptable conversion)

    return 0;
}

I am using Visual Studio 2010 in case this is behavior specific to my compiler. Thanks!
Posted

It is of course inherited as everything. The only problem is that the operator you defined is hidden by the default operator. You can easily see it if you cast a to Foo. Also note that Foo "=" returns the type Foo, and your code would require it to return Bar. There is no such operator, and this fact is indicated by the error you got.

For some background, please see:
http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29[^],
http://fedelebron.com/categorical-view-covariance-and-contravariance-c[^],
http://www.cpptips.com/Covariance.html[^],
http://stackoverflow.com/questions/1260757/when-is-c-covariance-the-best-solution[^] (please see the last answer),
http://itremarks.wordpress.com/2011/09/13/c-covariance-in-virtual-functions/[^].

—SA
 
Share this answer
 
Comments
CPallini 22-Oct-13 15:46pm    
5.
Sergey Alexandrovich Kryukov 22-Oct-13 15:58pm    
Thank you very much, Carlo.
—SA
Espen Harlinn 22-Oct-13 17:03pm    
5'ed!
Sergey Alexandrovich Kryukov 22-Oct-13 17:29pm    
Thank you, Espen.
—SA
It is inherited but hidden, see the answer to this Stack Overflow question: "operator= and functions that are not inherited in C++?"[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 22-Oct-13 15:58pm    
Same thing, my 5.
—SA
Espen Harlinn 22-Oct-13 17:01pm    
5'ed!
CPallini 23-Oct-13 3:16am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900