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?
Entity.h:
class Entity {
public:
Entity(int x, int y);
~Entity();
int x, y;
int sum = calculateSum();
private:
int calculateSum();
};
Entity.cpp:
#include "Entity.h"
Entity::Entity(int x, int y) {
this->x = x;
this->y = y;
}
Entity::~Entity() {
}
int Entity::calculateSum() {
return x + y;
}
main.cpp:
#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. :)