Home > Net >  Please help me out why I am getting error?
Please help me out why I am getting error?

Time:09-17

I can't figure it out why the Derived class remains Abstract after overriding function fun().

Here is the error message:

error: invalid new-expression of abstract class type 'Derived' Base *t = new Derived(a);
error: no matching function for call to 'Base::fun(int&)'int i = t->fun(b);
#include <iostream>
using namespace std;

class Base
{
protected:
    int s;

public:
    Base(int i = 0) : s(i) {}
    virtual ~Base() {}
    virtual int fun() = 0;
};

class Derived: public Base
{
public:
    Derived(int i) : Base(i) {}
    ~Derived() { cout << --s << " "; }
    int fun(int x) { return s * x; }
};

class Wrapper
{
public:
    void fun(int a, int b)
    {
        Base *t = new Derived(a);
        int i = t->fun(b);
        cout << i << " ";
        delete t;
    }
};

int main()
{
    int i, j;
    cin >> i >> j;
    Wrapper w;
    w.fun(i, j);
    return 0;
}

CodePudding user response:

The function has two different signatures between the base class and derived class

virtual int fun() = 0;

but then the derived class

int fun(int x) { return s * x; }

if you would add override it would alert you to this mistake

int fun(int x) override { return s * x; }

CodePudding user response:

The problem is that

int fun(int x) { return s * x; }

does not override

virtual int fun() = 0;

because the argument list is different (no arguments vs. a single int). If you'd written

int fun(int x) override { return s * x; }

as you should since C 11, then the compiler would have given you an error about this.

  • Related