Gone through many iterations in my head/on paper, and I'm not sure what the "best" or "most correct" way to go about this scenario.
Setup:
- I have a class 'A' provided to me. I cannot change this class. This class has several public methods.
- I have written class 'B' that takes many class 'A's and controls them as one, using the same method names to make A and B interchangeable in code.
- I now want to write class 'C' that can take a class 'A' or class 'B' (or another class in the future with the same public methods) to perform more complex operations.
I tried doing this by writing a "superclass" 'D' to have the common operations while 'C' could inherit 'D' and supply the varible type required. However 'D' cannot see the 'C' private variable.
I'm sure I'm just thinking about this structure wrong and so fouling up how to use inheritance properly here. Give that class D does now know the type of class C, I can't force-cast it. D is also going to have a lot of functions that require using 'o' and I was trying to avoid having to re-implement every one of them for each potential class type.
I'm also sure this is a common issue, but I've been searching for an answer for 2 days now...
Simplified example code:
// Class A has been provided to me, and cannot be modified.
#include <classA.h>
class B {
public:
B(A *x, int num): z(x), n(num) {};
int num(void) {return n;};
// Other methods to operate on objects of class A as if they were a single
// one, using same method names. Maybe somehow inheritance is better here?
private:
A *z;
int n;
};
class D {
public:
D(void): s(5) {};
// 'o' to be provided by child class, must have method 'num'
void doThat(void) {return s+o.num();};
private:
int s;
};
// So we can handle multiple types of devices that have the same public methods
// This is just a class to get the private object that superclass D will need
class C: public D {
public:
C(B *h): o(h) {};
private:
B *o;
};
A ar[2] = { A(1), A(2) };
B l(ar, 2);
C j(&l);
This gets me the error that 'o' is not in scope.
Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"
sketch_feb11b.ino: In member function 'void D::doThat()':
sketch_feb11b:26: error: 'o' was not declared in this scope
void doThat(void) {return s+o.num();};
exit status 1
'o' was not declared in this scope
I'm newly back to C++ after many many years, so I'm also just as willing to accept I'm not approaching the problem correctly in the first place now.