Ste Prescott
Ste Prescott

Reputation: 1817

Subclass calling Base Class constructor then using instance method of Base Class in Subclass Arduino C++

I have a Base Class FCBRelay and within that class it deals with setting up of the relay to a pin and holding general methods such as on or onForTime.

When I attempt to call onForTime within the Subclass it won't compile giving the error:

cannot call member function 'void FCBRelay::onForTime(int)' without object

Now I understand what the error is saying as the onForTime method is not static but my Subclass constructor calls the Base Class constructor too. Or so says my understanding.

The idea of this is to be more descriptive in my main function. Rather than calling waterPump.onForTime(2); I could call waterPump.squirt(2);

My Classes are as below


FCBRelay.h

#ifndef FCBRelay_H
#define FCBRelay_H

#include <Arduino.h>

class FCBRelay {
  public:
    FCBRelay(int pinNo);

    int delayTime;

    void tick();
    void onForTime(int timeInSeconds);

  private:
    int _pinNumber;
    int _lastTickMillis;

    void on();
    void off();
};

#endif

FCBRelay.cpp

#include "FCBRelay.h"

FCBRelay::FCBRelay(int pinNo) {
  _pinNumber = pinNo;
  pinMode(_pinNumber, OUTPUT);
}

void FCBRelay::onForTime(int timeInSeconds) {
  delayTime = timeInSeconds * 1000;
  on();
}

void FCBRelay::tick() {
  unsigned long currentMillis = millis();
  if((currentMillis - _lastTickMillis) >= delayTime) {
      _lastTickMillis = currentMillis;
      off();
  }
}

void FCBRelay::on() {
  digitalWrite(_pinNumber, HIGH);
}

void FCBRelay::off() {
  digitalWrite(_pinNumber, LOW);
}

FCBWaterPump.h

#ifndef FCBWaterPump_H
#define FCBWaterPump_H

#include "FCBRelay.h"

class FCBWaterPump : public FCBRelay {
  public:
    FCBWaterPump(int pinNo);

    void squirt(int timeInSeconds);
};

#endif

FCBWaterPump.cpp

#include "FCBWaterPump.h"

FCBWaterPump::FCBWaterPump(int pinNo) : FCBRelay(pinNo) {

}

void squirt(int timeInSeconds) {
  FCBRelay::onForTime(timeInSeconds);
}

Any help would be great, thanks.

Upvotes: 0

Views: 1421

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63830

You accidentally wrote a stand-alone function. That's why there's no object.

Change this:

void squirt(int timeInSeconds) {
  FCBRelay::onForTime(timeInSeconds);
}

to this:

void FCBWaterPump::squirt(int timeInSeconds) {
//   ^^^^^^^^^^^^^^
  FCBRelay::onForTime(timeInSeconds);
}

Upvotes: 4

Related Questions