views:

213

answers:

2

Let's suppose I have a class Dog that inherits from class Animal, you might want to insert a call to Animal::operator= in Dog::operator=.

What is the most readable/common way to write it?

I think I know those two...

static_cast<Animal*>(this)->operator=(other);

and

this->Animal::operator=(other);
+6  A: 

this->Animal::operator=(other); is the correct way, you fully qualify the method referring to your parent implementation, you don't need to cast yourself for that and it makes the code harder to read.

Arkaitz Jimenez
Alexandrescu would also use: `Animal me = other;`. I am not sure I understand the exact purpose of this though, but it is clean and produces (as far as I can tell) the same effect.
Matthieu M.
As @AndreyT said, you have the danger of operator= being virtual, you could end in endless recursion, apart from not having called the method you wanted.
Arkaitz Jimenez
... except that this "Alexandrescu" variant might also lead to infinite recursion in case of virtual assigment operators. Yes, I know that a virtual assigment operator is not exactly something that one sees very often (if at all), but as a generic method (i.e. not for assignment operators only) this is seriously broken.
AndreyT
+10  A: 

Since you are doing it from within a child class method

Animal::operator=(other);

No need for this->. The scope resolution syntax does exactly what was requested. I don't see a point in doing it "indirectly" with a cast.

Note also that doing it with a cast might not produce the expected result in general case, since it will not disable the dynamic resolution of virtual method call. (And, BTW, assignment operator can be declared virtual). An obvious consequence of that is that with virtual methods the "cast" variant might easily result in endless recursion.

AndreyT
In fact, it probably *should* be virtual if you're overriding it in a derived class: you're almost certainly going to get unwanted behavior at some point.
mos
@mos: Usually, when someone is talking about "assignment operator", they mean the copy-assignment operator. Copy-assignment operators don't override each other in the hierarchy since their signatures are different from class to class (different parameter types). So, your reasoning does not apply to copy-assignment operator. It might not apply to any assignment operator, because it is a special member function with its own rules.
AndreyT
@mos: ... But in general case the danger is there, even with assignment operators.
AndreyT
Correct one: no need for `this` unless `Animal` is a template.
Pavel Shved
@Pavel Shved: Err... Not sure what you mean (I could be missing something). `this->` with templates is used to force lookup of an *unqualified* name in dependent base type. Alternative approach is to use a *qualified* name. In this case we already have a qualified name. What would be the point of adding `this->`?
AndreyT