I am writing a library with chainable methods.
class Base {
protected:
int stepper=0;
public:
Base& baseMethod( void ) {
Serial.println( stepper );
return *this;
}
virtual Base& derivedMethod( void ) =0;
virtual Base& anotherDerivedMethod( void ) =0;
};
class Derived1 : public Base {
public:
Derived1& derivedMethod( void ) {
stepper += 1;
return *this;
}
Derived1& anotherDerivedMethod( void ) {
stepper -= 1;
return *this;
}
};
class Derived2 : public Base {
public:
Derived2& derivedMethod( void ) {
stepper += 2;
return *this;
}
Derived2& anotherDerivedMethod( void ) {
stepper -= 2;
return *this;
}
Derived2& specialMethod( void ) {
stepper *= 2;
return *this;
}
};
As you can see, baseMethod()
returns a reference to a Base
class, so I wouldn't expect to be able to then chain derivedMethod()
or anotherDerivedMethod()
to it, because the Base
class should have no access to any derived methods.
However, in my test code (written for Arduino):
Derived1 myDerived1;
Derived2 myDerived2;
void setup() {
Serial.begin( 9600 );
// as expected, these work:
myDerived1.derivedMethod().baseMethod(); // prints 1
myDerived1.derivedMethod().derivedMethod().baseMethod(); // prints 3
myDerived1.anotherDerivedMethod().baseMethod(); // prints 2
myDerived1.anotherDerivedMethod().derivedMethod().baseMethod(); // prints 2
myDerived2.specialMethod().baseMethod(); // prints 0
myDerived2.specialMethod().derivedMethod().baseMethod(); // prints 2
myDerived2.derivedMethod().specialMethod().baseMethod(); // prints 8
// I wouldn't expect these to work, but I'm glad they do!
myDerived1.baseMethod().derivedMethod(); // prints 2
myDerived1.baseMethod().anotherDerivedMethod(); // prints 3
myDerived2.baseMethod().derivedMethod(); // prints 8
myDerived2.specialMethod().baseMethod().derivedMethod(); // prints 20
// and as expected, these don't work:
myDerived2.baseMethod().specialMethod(); // prints 22
myDerived2.baseMethod().derivedMethod().specialMethod(); // prints 24
}
void loop() { }
I can chain derivedMethod()
and anotherDerivedMethod()
to baseMethod()
, but I can't chain specialMethod()
to it.
method_chaining.ino:76:27: error: 'class Base' has no member named 'specialMethod'
The only difference I can see is that specialMethod()
isn't mentioned in the Base
class definition. Is that why it doesn't work?
How can I chain derived class methods to base class methods?