8

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

  • 3
    No, currently that's not possible. – Quimby Jul 02 '19 at 14:08
  • 2
    Currently not. Unfortunately paper N2965 [was rejected](https://stackoverflow.com/a/33664204/1870760) otherwise you could've used `std::direct_base` along with a type alias. Maybe soon (TM). – Hatted Rooster Jul 02 '19 at 14:11
  • 4
    If you are using Visual C++ (Visual Studio), you can use [`__super`](https://learn.microsoft.com/en-us/cpp/cpp/super?view=vs-2019). Otherwise, this is a relevant read: https://stackoverflow.com/questions/180601/using-super-in-c – Algirdas Preidžius Jul 02 '19 at 14:11

1 Answers1

6

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();
  }
};
BiagioF
  • 9,368
  • 2
  • 26
  • 50
  • 3
    The same advice as discussed in the linked question applies here as well. Best to make the alias private. – eerorika Jul 02 '19 at 14:32