Reputation: 22977
I'm trying to play some around with classes in C++. Coming from a Java world, they're slightly different.
What I'm trying to do should be obvious: I have a class named SomeClass
, which holds a single int
. Then I have a class named A
, which
// Create a class holding just an integer.
class SomeClass {
public:
int _value;
SomeClass(int value) {
this->_value = value;
}
};
class A {
private:
// The property _someClassPointer holds a pointer to a SomeClass object.
SomeClass *_someClassPointer;
public:
// We can set a SomeClass instance as a property of the A class.
void setSomeClass(SomeClass *someClassPointer) {
// It copies the local pointer value to the property.
this->_someClassPointer = someClassPointer;
}
// We can retrieve the integer that the SomeClass instance holds.
// We're assuming _someClassPointer does not point to NULL.
int getValueOfSomeClass() {
this->_someClassPointer->_value;
}
};
void setup() {
Serial.begin(9600);
}
void loop() {
// Instantiate SomeClass object with int(5) argument
SomeClass someClass(5);
Serial.println(someClass._value); // It prints 5, as expected
// Instantiate an A object by its default constructor
A a;
// Pass the address of someClass to the method
a.setSomeClass(&someClass);
// Set the value of someClass to 6
someClass._value = 6;
Serial.println(a.getValueOfSomeClass()); // It prints 0
}
How come 0
is printed instead of 6
?
Upvotes: 0
Views: 121
Reputation: 787
2nd Question: It's the diference between passing arguments by value, by reference and by pointer. Its a little tricky, but you can find a lot of info in the web about this topic.
Upvotes: 0
Reputation: 1729
Your function is not returning a value.
int getValueOfSomeClass() {
return this->_someClassPointer->_value;
}
EDIT: I should mention that you can remove the 'this->' because it is implied in non-static method.
int getValueOfSomeClass() {
return _someClassPointer->_value;
}
Upvotes: 6