raneshu
raneshu

Reputation: 413

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;
}

Upvotes: 0

Views: 56

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117886

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.

Upvotes: 3

Related Questions