1

I have a MotorDefinition class and an abstract class called Motor:

class MotorDefinition {
public:
    MotorDefinition(int p1, int p2, int p3) : pin1(p1), pin2(p2), pin3(p3) {}
    int pin1 = -1;
    int pin2 = -1;
    int pin3 = -1;
};
class Motor {
public:
     Motor(MotorDefinition d) : definition(d) {}
     virtual void forward(int speed) const = 0;
     virtual void backward(int speed) const = 0;
     virtual void stop() const = 0;
protected:
    MotorDefinition definition;
};

My Zumo vehicle has two motors:

class MotorTypeZumoLeft : public Motor {
    MotorTypeZumoLeft(MotorDefinition def) : Motor(def) {}
    void Motor::forward(int speed) const {}
    void Motor::backward(int speed) const {}
    void Motor::stop() const {}
};

class MotorTypeZumoRight : public Motor {
    MotorTypeZumoRight(MotorDefinition def) : Motor(def) {}
    void Motor::forward(int speed) const {}
    void Motor::backward(int speed) const {}
    void Motor::stop() const {};
};

class MotorTypeZumo {
public:
     MotorTypeZumo(MotorTypeZumoLeft *l, MotorTypeZumoRight *r) : left(l), right(r) {}

protected:
    MotorTypeZumoLeft *left;
    MotorTypeZumoRight *right;

};

Unfortunately (for me), this doesn't compile:

MotorDefinition lmd(1, 2, 3);
MotorTypeZumoLeft *leftMotor(lmd);
MotorDefinition rmd(4, 5, 6);
MotorTypeZumoRight *rightMotor(rmd);
MotorTypeZumo motors(*leftMotor, *rightMotor);

I think I am missing some fundamental concepts and I am certainly messing up some syntax. Can you help me define this correctly, please.

Bob Jones
  • 2,049
  • 5
  • 32
  • 60

1 Answers1

0

The following doesn't work, because you cannot initialize a pointer variable with a MotorDefinition instance.

MotorTypeZumoLeft *leftMotor(lmd);

You probably did not intend leftMotor to be a pointer.

MotorTypeZumoLeft leftMotor(lmd);

Similarly for rightMotor.

MotorTypeZumoRight rightMotor(rmd);

You need to pass addresses to initialize motors:

MotorTypeZumo motors(&leftMotor, &rightMotor);

However, if you did intend for leftMotor and rightMotor to be pointers, it would be better to use a smart pointer rather than a raw pointer.

auto leftMotor = std::make_unique<MotoTypeZumoLeft>(lmd);
auto rightMotor = std::make_unique<MotoTypeZumoRight>(lmd);

And, you should modify MotorTypeZumo to also use smart pointers.

class MotorTypeZumo {
public:
     MotorTypeZumo(
          std::unique_ptr<MotorTypeZumoLeft> &l,
          std::unique_ptr<MotorTypeZumoRight> &r)
    : left(std::move(l)), right(std::move(r)) {}
protected:
    std::unique_ptr<MotorTypeZumoLeft> left;
    std::unique_ptr<MotorTypeZumoRight> right;
};

Then, you can just pass leftMotor and rightMotor to motors.

MotorTypeZumo motors(leftMotor, rightMotor);
jxh
  • 69,070
  • 8
  • 110
  • 193