Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ call an overriden virtual function with a derived argument

How can I call an overridden virtual function with a derived argument?

The argument I’m calling it with is of a derived class of the argument it was defined and overriden with.

//Args
struct ArgBase{
    int val;
};

struct ArgDerived: ArgBase{
    int derivedVal;
};


/////

struct Base {
    int name;
    virtual int doSomething(ArgBase a) = 0;
};

struct Derived: public Base {
    int doSomething(ArgBase a){ //I want to overide Base's virtual function, so I need to pass in an ArgBase here (and not an ArgDerived)
        
        return a.derviedVal; //<------------- how can I get this to work?
        // option 1: return static_cast<ArgDerived>(a).derviedVal; does not work
        // option 2: can I may be do something like "if(a is ArgDerived){....}"?
    }
};

int main ()
{
  Derived d;//object of derived class

  ArgDerived ad; //object of derived argument class
  ad.val = 25;
  ad.derivedVal = 75;
  
  std::cout << d.doSomething(ad) << std::endl; //<---------- call with derived argument ad
  return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should accept the argument by reference or pointer for it to behave polymorphically

virtual int doSomething(const ArgBase& a) = 0;

then you can cast in your overriden function

return static_cast<const ArgDerived&>(a).derviedVal;

of course static_cast assumes that this cast is valid at runtime. If you are unsure of the derived type being passed then you’d need to use something like dynamic_cast which will throw a std::bad_cast if the reference is not of that type. Or use some other pattern, but the point being you must only static_cast if that type is appropriate at runtime.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading