Reputation: 1365
Suppose I wanted to overload the "==" operator for a derived class, do I need to rewrite the overload in the derived class header file or is there a way to implement the operator overload in the .cpp file without having to add anything in the header file? And if so, how would the implementation of the derived operator look like in the .cpp?
What my header looks like:
class A
{
public:
A();
~A();
virtual bool operator==(const A &ref) = 0;
protected:
int year;
string note;
}
class B:A
{
public:
B();
~B();
bool operator==(const B &ref); //is this needed or not?
private:
int month, day;
}
Upvotes: 9
Views: 19830
Reputation: 421
Function signatures in C++ method overriding have to match exactly (except for the return type if the return type is a pointer):
class A { ... };
class B : A { ... };
class A: virtual bool operator==(const A &ref) = 0;
class B: bool operator==(const A &ref) override; // OK
class B: bool operator==(const B &ref) override; // Invalid
If class B derived from A isn't overriding a method declared in A as virtual T foo() = 0
then class B is an abstract class.
See also the following terms:
Upvotes: 10
Reputation: 31
As stated in previous answers, you have to define the function in the derived class. Also when overriding, one should always use the keyword: override
.
In your example,
virtual bool operator==(const A &ref) = 0;
is not overriden by
bool operator==(const B &ref);
Even if you define the latter, the class B will still be abstract. If the operator==
in B is declared as
bool operator==(const B &ref) override;
then the compiler will produce an error informing us that this function does not override anything.
Upvotes: 3
Reputation: 311038
The function has to be redeclared in the derived class. Otherwise 1) the derived class will be also abstract and 2) you may not define a member function of a class if it was not at first declared in this class.
Take into account that the function declaration should look like
virtual bool operator==(const A &ref) const = 0;
^^^^^
Upvotes: 1
Reputation: 409206
If you want to override a virtual function in a child-class, then you need to declare the function override in the child class.
So yes, the declaration is needed.
Think about it this way: The class declaration could be used in many places and many source files, how else would the compiler know that the function has been overridden?
Upvotes: 8