calling operators of base class... safe?
29,928
Solution 1
This is fine, but it's a lot more readable IMHO to call the base-class by name:
Base::operator = (rhs);
Solution 2
Yes, it's safe.
A different syntax to do the same thing could be:
Base::operator=( rhs );
Solution 3
That's better to use
Base::operator=(rhs);
because if your base class have a pure virtual method the static_cast is not allowed.
class Base {
// Attribute
public:
virtual void f() = 0;
protected:
Base& operator(const Base&);
}
class Derived {
public:
virtual void f() {};
Derived& operator=(const Derived& src) {
Base::operator=(src); // work
static_cast<Base&>(*this) = src; // didn't work
}
}
Author by
smerlin
Updated on November 26, 2020Comments
-
smerlin over 3 years
Is following pattern ok/safe ? Or are there any shortcomings ? (I also use it for equality operators)
Derived& operator=(const Derived& rhs) { static_cast<Base&>(*this) = rhs; // ... copy member variables of Derived return *this; }
-
smerlin over 13 yearsindeed... just noticed that this notation works for implicitly defined assignement operators aswell (always thought that it would only work for explicitly defined ones)
-
BЈовић over 13 yearsactually this is a better way, then needing to cast. Also, this should be done in the derived classes