I want to learn how to use class object within class, especially how to pass an arguments between the objects. I'm trying to create an example object Calc which should provide two methods Calc.sum and Calc.sub. It should use another object Plus as a math engine. The Plus.add function compile and works well. But I don't know how to initiate multiple instance of plus in the calc. The code:
class Plus{ // This class works well
public:
Plus(int); // Structure
int add(int); // Public method (function)
int myVar; // Public property. Just to hold a value.
private:
int _init; // Class-level private variable
};
Plus::Plus(int init){ // Constructor
_init = init;
}
int Plus::add(int p){ // Method add
return _init + p;
}
/***************************************************************************/
class Calc{
public:
Calc(int); // Structure
int sum(int); // Method sum
int sub(int); // Method sub
int myVar; // Public property
private:
Plus positive(int); // Class-level private object definition ?
Plus negative(int); // This is probably wrong ??
};
Calc::Calc(int init){ // Constructor (also wrong...)
Plus positive(init); // Create object "positive" and pass the initial value
Plus negative(-init); // Create object "negative" and pass the initial value
}
int Calc::sum(int n){
return positive.add(n);
}
int Calc::sub(int n){
return negative.add(n);
}
/***************************************************************************/
Plus two(2); // Create class object two
Calc five(5); // Create class object five
void setup(){
Serial.begin(115200);
Serial.print("two.add(3) = ");
Serial.println(two.add(3)); // Calling instance of class Plus
two.myVar = 100;
Serial.println(two.myVar);
Serial.print("five.sum(3) = ");
Serial.println(five.sum(3)); // Calling instance of class Calc
Serial.print("five.sub(3) = ");
Serial.println(five.sub(3)); // Calling instance of class Calc
}
void loop(){}
My example is inspired by this article: http://arduinoetcetera.blogspot.cz/2011/01/classes-within-classes-initialiser.html but the code there is for one instance only
1) How to declare multiple instances of Plus within Calc
2) Is the terminology (comments) right?