Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you explicitly use an ancestor's virtual class method as a derived method?

Tags:

c++

oop

Is it possible to explicitly use a distant ancestor's virtual function after it's already been overridden? Something similar to the following?


class A {
    virtual void task();
};

class B: public A {
    virtual void task() override;
};

class C: public B {
    virtual void task() = A::task; /* C++ doesn't like this */
};

I really don't want to have to re-implement something that's already been implemented. It seems it's technically possible because c++ uses a virtual table to point to class methods, so behind the scenes it should be able to put A's method pointer in the table as if it were never overridden in the first place.

I do NOT want to do this:


class C: public B {
    virtual void task() {
        A::task();
    }
};

like image 808
Warpspace Avatar asked Mar 13 '23 23:03

Warpspace


2 Answers

Where you want to use the method implementation in class A you can simply call it like A::task().

That's a non-virtual call.


Regarding

c++ uses a virtual table to point to class methods

… no, that's not so, although that's the common implementation.


Regarding

I do NOT want to do this:

class C: public B {
  virtual void task() {
      A::task();
  }
}

… that's the way to do it if you want task in class C to act as if it is the A::task implementation.

like image 152
Cheers and hth. - Alf Avatar answered Apr 26 '23 20:04

Cheers and hth. - Alf


You said:

I do NOT want to do this:

class C: public B {
   virtual void task() {
      A::task();
   }
};

I think this is the best solution given the current state of the standard.

like image 29
R Sahu Avatar answered Apr 26 '23 18:04

R Sahu