Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an interface needs to be redeclared?

I have an abstract base class and want to implement a function in the derived class. Why do I have to declare the function in the derived class again?

class base {
public:
    virtual int foo(int) const = 0;
};

class derived : public base {
public:
    int foo(int) const; // Why is this required?
};

int derived::foo(int val) const { return 2*val; }
like image 334
Michael Avatar asked Jun 27 '12 09:06

Michael


5 Answers

The intention of making a function pure virtual in Base class is that the derived class must override it and provide its own implementation.
Note that presence of an pure virtual function in the class makes that class an Abstract class. In simple terms the class acts as an interface for creating more concrete classes.One cannot create objects of an Abstract class.

If you do not override the pure virtual function in derived class then the derived class contains the inherited Base class pure virtual function only and it itself acts as an Abstract class too.Once your derived class is abstract it cannot be instantiated.
So in order that your derived class be instantiated it needs to override and hence declare the pure virtual function.

like image 40
Alok Save Avatar answered Nov 20 '22 04:11

Alok Save


Consider that the derived-class definition might be in a header, whereas its implementation may be in a source file. The header typically gets included in multiple locations ("translation units"), each of which will be compiled independently. If you didn't declare the override, then the compiler wouldn't know about it in any of those other translation units.

like image 94
Oliver Charlesworth Avatar answered Nov 20 '22 03:11

Oliver Charlesworth


You might think the compiler can deduce that you're going to have to provide an implementation of derived::foo(), but derived could also be an abstract class (and in fact that's what you'll get if you dont declare foo() in derived)

like image 2
Michael Anderson Avatar answered Nov 20 '22 04:11

Michael Anderson


It is to override the abstraction of the base class.

If you do not re-declare it, then your derived class is also an abstract class. If you do then you now have a non-abstract type of the base.

like image 1
Ozair Kafray Avatar answered Nov 20 '22 02:11

Ozair Kafray


Because the hierarchy could have more layers.

struct Base {
    virtual void foo() const = 0;
    virtual void bar() const = 0;
};

struct SuperBase: Base {
     virtual void bar() const override;
};

struct Concrete: SuperBase {
     virtual void foo() const override;
};

Here, SuperBase does not provide an implementation for foo, this needs be indicated somehow.

like image 1
Matthieu M. Avatar answered Nov 20 '22 04:11

Matthieu M.