Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a derived class that inherits a final function but creates the same function (not override)?

I have a problem with a final function. I want to "stop" the polymorphism in a class but I still want to generate the same function in a derived class.

Something like this:

class Base{
    protected:
        int _x, _y;
    public:
        Base(int x = 0, int y = 0) : _x(x), _y(y){};
        int x() const { return _x; }
        int y() const { return _y; }
        virtual void print()const{ cout << _x*_y << endl; }
};

class Derived : public Base{
    public:
        Derived(int x = 0, int y = 0) : Base(x, y){}
        void print()const final { cout << _x*_y / 2.0 << endl; } // final inheritance
};

class NonFinal : public Derived{
        void print()const{ cout << "apparently im not the last..." << endl } 
    // here i want a new function. not overriding the final function from Derived class
};
like image 847
l.i.s. Avatar asked Jun 22 '17 17:06

l.i.s.


1 Answers

I think this is an experimental question, since actually you should rethink what you are doing when you require to "override a final function" (sounds contradicting, doesn't it?).

But you could introduce a "dummy"-parameter, i.e. void NonFinal::print(int test=0)const, which let's the compiler treat the member function as a different one. Not sure if that solves your "problem"; but at least it introduces a function with the same name, which can still be called without passing an argument, and which is separated from the ones of Derived and Base.

class NonFinal : public Derived{
public:
    void print(int test=0)const{ cout << "apparently im not the last..." << endl; }
};

int main() {

    Base b (10,10);
    Derived d (20,20);
    NonFinal nf;
    Base *bPtr = &d;
    bPtr->print();  // gives 200
    bPtr = &nf; // gives 0
    bPtr->print();
    nf.print(); // gives "apparantly..."
}
like image 200
Stephan Lechner Avatar answered Nov 12 '22 07:11

Stephan Lechner