jeudi 18 novembre 2021

C++ How to invoke override-function from base class virtual-function [closed]

I have a question related to inheritance in C++.

Let's say I have a derived-class instance ins that has been upcasted for whatever reason. The question is how do I invoke ins's derived-class methods from the virtual methods?

It is better explained in the example below.

class Base {
  virtual void Print() {
    // Does something

    // How do I invoke the subclass's Print()?
    
    // Does something
  }
};

class Derive1 : public Base {
    int a;  // Derive1's fields are very different than Derive2's
  int b;
  
  void Print() override {
    // Does something
  }
};

class Derive2 : public Base {
  float a;
  float b;
  
  void Print() override {
    // Does something
  }
};

int main() {
  std::vector<Base> vec;  // Necessary to upcast the subclasses
  // Init vec
  vec[0].Print();  // I want this to also invoke the derived class's Print()
}

Currently, I have attempted to do something along this line :

class Base {
  virtual void Print() {
    // Does something
    if (dynamic_cast<Derive1*>(this)) {
      this->Print();  // How else do I invoke the subclass's Print()?
    }
    else if (dynamic_cast<Derive2*>(this)) {
      this->Print();
    }
    // Does something
  }
};

But I imagine this will invoke the base class Print() again and goes into an infinite loop.

Thank you!

Aucun commentaire:

Enregistrer un commentaire