As per this answer using same name for both member variable and constructor argument is fine. So after doing some debugging, I figured why the below code was not working (the operation member of the class was never getting initialized causing the switch statements to fail.)
#include <cstdio>
#include <cstdlib>
enum class Operator {
Add,
Subtract,
Multiply,
Divide
};
class Calculator {
Operator operation;
public:
Calculator(Operator operation) {
operation = operation;
}
int calculate(int a, int b) {
switch (operation) {
case Operator::Add: {
return a+b;
}
case Operator::Subtract: {
return abs(a-b);
}
case Operator::Multiply: {
return a*b;
}
case Operator::Divide: {
return a/b;
}
}
}
};
int main() {
Calculator calculator{Operator::Add};
int a = 100;
int b = 20;
printf("%d + %d = %d\n", a, b, calculator.calculate(a, b));
}
replacing the line operation = operation
with operation{operation}
inside constructor fixed the issue, but I am still not getting why operation = operation
was producing wrong results compared to operation{operation}
and what's the difference between both in context of constructor initialization;