1

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?

Ja5onHoffman
  • 618
  • 8
  • 16
  • 1
    You haven't shown any reason you would want an explicit cast at all. The code is fine as you showed it. The compiler would do the correct implicit cast. There could be some more complex extension of your example that calls for an explicit cast. But then answering your question would depend on details you haven't shown. – JSF Oct 30 '15 at 16:42
  • Ok. New to C++. Maybe preparing for a problem I don't have. You can make your comment an answer or I can delete the question. – Ja5onHoffman Oct 30 '15 at 16:45
  • There's nothing wrong with your code, but it's prone to memory leaks. Consider refactoring to [avoid using new and delete](http://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new). – Jared Dykstra Oct 30 '15 at 16:54

1 Answers1

1

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.

Jared Dykstra
  • 3,487
  • 10
  • 24