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;
}
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.
C does not support operator overloading at all. You can only implement operations as functions: Colour colour_add(Colour c1, Colour c2); Colour colour_substract(Colour c1, Colour c2); ...
This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
A virtual function must be defined in the base class, even though it is not used. The prototypes of a virtual function of the base class and all the derived classes must be identical. If the two functions with the same name but different prototypes, C++ will consider them as the overloaded functions.
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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With