1

Is it possible to write a C++ class that controls an object that can be of a derived type, without using a pointer?

Example

class Car {
   public:
      void Honk();
};
class RedCar : public Car {}
class CarController {
   public:
     CarController(Car car);
     Car car;
     void Honk();
}

void CarController::Honk(){
   this->car.Honk();
}

RedCar redcar;
CarController controller(redcar);
controller.Honk();
errno_44
  • 151
  • 6
  • You can also use references. If the question is really "is it possible without pointers or references," the answer is no. The line `CarController controller(redcar);` will [slice](https://stackoverflow.com/q/274626/501250) `redcar` and _convert it_ to a `Car` object. – cdhowie Nov 01 '19 at 19:01
  • Maybe (if there is no runtime polymorphism) you are looking for *class templates*? – walnut Nov 01 '19 at 19:02
  • This is true. `CarController` could be made a template class. It depends whether the types are known fully at compile-time, or if some runtime logic will decide which type of car to use. – cdhowie Nov 01 '19 at 19:05

0 Answers0