Ja5onHoffman
Ja5onHoffman

Reputation: 672

Pass derived class to function defined to take base class arguments

If I have a base class and a derived class, such as:

class Base {
protected:
  int a;
public:
  void setA(int);
  void getA(int);
}

class Derived : public Base {
private:
  int b;
public:
  void doThing();
}   

Then a third, additional class that uses the base class:

class OtherClass {
public:
  Base doClassThing(Base*, Base*);
}

What's the best way to pass the derived class to a function that's defined to return a base class and take the base class as an argument. Like this:

Derived *x = new Derived();
Derived *y = new Derived();

doClassThing(x, y);

Would I pass the objects with a type cast? Or should I type cast the objects when they're first created?

Upvotes: 1

Views: 1206

Answers (1)

Jared Dykstra
Jared Dykstra

Reputation: 3626

To answer your two questions:

  • You would not cast the objects when they're first created.

  • There is no need to cast when calling; You do not need to modify the code in your question.

Upvotes: 1

Related Questions