Question

What I would like to do is similar to this (working):

class Claw {
  public:
    Claw(int pin);
  private:
    int pin;
  };

Claw::Claw(int pinNumber) {
  pin = pinNumber;
  }

But I want to do it with classes instead of basic types. I want to define the class in the private section (so I can use it on all the object) and execute the AccelStepper constructor in the Wheel constructor. I've tried these two solutions and they both give different errors:

class Wheel {
  public:
    Wheel(int pin);
  private:
    AccelStepper stepper;
  };

Wheel::Wheel(int pinNumber) {

  // This doesn't work
  AccelStepper stepper(AccelStepper::DRIVER, pinNumber, 1);

  // This also doesn't work
  stepper(AccelStepper::DRIVER, pinNumber, 1);
  }

How can I achieve what I'm trying to do?

Note that this works, but I cannot pass the pin number then:

class Wheel {
  public:
    Wheel();
  private:
    AccelStepper stepper(5);
  };

Wheel::Wheel() {
  }
Was it helpful?

Solution

You do it with a member initialization list:

Wheel::Wheel(int pinNumber)
    : stepper(AccelStepper::DRIVER, pinNumber, 1)
{
}

OTHER TIPS

In your header:

class Wheel
{
public:
    class Stepper; // Forward declaration of embedded class

    Wheel();
    Stepper& stepper() { return *_pStepper; }

private:

    Stepper* _pStepper;
};

In your implementation:

class Wheel::Stepper
{
public:
    void accelerate() {}
};

Wheel::Wheel()
    : _pStepper( new Stepper() )
{
    stepper().accelerate();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top