I’m having some trouble with the class casting in C++.
To learn, I wanted to create a class which just make operations, like sums, but it seems to crash everytime I launch it.
Here is my simple classes:
#include <iostream>
class CCalculation {
public:
CCalculation() {};
virtual int calculate() = 0;
};
class CCalc_CONST : public CCalculation {
int x;
public:
CCalc_CONST(int a) : x(a) {};
int calculate() { return x; };
};
class CCalc_ADD : public CCalculation {
CCalculation *x;
CCalculation *y;
public:
CCalc_ADD(CCalculation *a, CCalculation *b) {
this->x = a;
this->y = b;
};
int calculate() {
std::cout << "Calculation...\n";
return x->calculate() + y->calculate();
};
};
And my test:
CCalculation *a = &CCalc_CONST(4);
CCalculation *b = &CCalc_CONST(1);
CCalculation *c = &CCalc_ADD(a,b);
std::cout << "res: " << c->calculate() << "\n";
It seems to crash everytime (I got no compiler error or warning).
The only way to run it I found is when I’m printing a->calculate and b->calculate at the CCalc_ADD construction. I have absolutely no clue why i need to call the calculate function to make it work.
Can someone please explains to me how to actually do it ?
You’re not using new. Test like this:
You can weed out things like address-of on temporaries by compiling with
-Wall, which enables all compiler warnings. The compiler is your friend and is there to help. Love the compiler.