Why can't I simply call a class object attribute (i.e. sum
) that calls a calls method (i.e. calculateSum()
) that returns the value that attribute should have? What am I overlooking here? I know about how getter and setter functions are usually used, but I like the shortcut of simply calling an attribute that gets then itself updated with a method?
class Entity {
public:
Entity(int x, int y);
~Entity();
int x, y;
int sum = calculateSum();
private:
int calculateSum();
};
#include "Entity.h"
Entity::Entity(int x, int y) {
this->x = x;
this->y = y;
}
Entity::~Entity() {
}
int Entity::calculateSum() {
return x + y;
}
#include <iostream>
#include "Entity.h"
int main() {
entity = Entity(5, 7);
std::cout << entity.sum << std::endl; // outputs 0, should be 12!!
}
Is this even possible? Or are there any alternatives?
Thanks. :)
In your code, the initialization order for class Entity
is:
x
is default-initialized to indeterminate valuey
is default-initialized to indeterminate valuesum
is initialized as calculateSum()
x
and y
are assigned to the function parameters).As you can see, when data member sum
is initialized from calculateSum()
, in which the data member x
and y
are used but they're just default-initialized, still not get assigned as you expected in the constructor body.
You can initialize them in member initializer list.
Entity::Entity(int x, int y) : x(x), y(y) {
}
Then the order would be (same as the above in concept, but effect changes):
x
is direct-initialized to the constructor parameter x
y
is direct-initialized to the constructor parameter y
sum
is initialized as calculateSum()
LIVE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With