Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling base class method in derived class without specifying base class name

When overriding a C++ virtual method, is there a way to invoke the base class method without specifying the exact base class name, in a similar way that we can do it in C# with the "base" keyword? I am aware that this could be in conflict with multiple inheritance, but I wonder if more modern versions of C++ have introduced such a possibility. What I want to do is something like this:

class A
{
  public:
  virtual void paint() {
    // draw something common to all subclasses
  }
};

class B : public A
{
  public:
  virtual void paint() override {
    BASE::paint();
    // draw something specific to class B
  }
};

I know that in B::paint() we can call A::paint(), I just want to know if there is a more "generic" way to call the base method without referring explicitly to class A. Thank you in advance. Andrea

like image 828
Andrea Buzzelli Avatar asked Jul 02 '19 14:07

Andrea Buzzelli


1 Answers

No, there is no fancy keyword to access to the base class. As some comments already mentioned, some proposals have been rejected by the standard committee.

Personally, in some contexts, I opt for a typedef/using directive; especially when my hierarchy has templated classes.

For instance:

template <typename T>
class A {};

template <typename U, typename T>
class B : public A<T> {
 private:
  using Base = A<T>;

 public:
  void foo() {
    // Base::foo();
  }
};
like image 166
BiagioF Avatar answered Nov 14 '22 15:11

BiagioF