This is more of a preferred style question when working in c++. I am looking for preferred standards around this.
Say I have an interface A
class AInterface {
public:
virtual ~AInterface() = default;
virtual void a() = 0;
};
And then I have another interface B that is built on top on A
class BInterface : public AInterface{
public:
virtual void b() = 0;
virtual void otherb() = 0;
};
My question is should I redeclare all the virtual functions from AInterface in B like so?
class BInterface : public AInterface{
public:
virtual void a() = 0;
virtual void b() = 0;
virtual void otherb() = 0;
};
No. You do not have to.
...and you should not, because it is unnecessary duplication without benefit. If you do, at least use the override
keyword to avoid a mismatch in the declarations.
Imagine you change the base to
class AInterface {
public:
virtual ~AInterface() = default;
virtual void a(int) = 0;
};
and you forget to update BInterface
, then whoops, now you have a void a()
in BInterface
that was not intended. If however you have override
:
class BInterface : public AInterface{
public:
virtual void a() override = 0;
virtual void b() = 0;
virtual void otherb() = 0;
};
You would get a compiler error, because after the above refactoring void a()
does not override a method from its base.