#include <iostream>
enum types { INTEGER, DOUBLE, BOOL, STRING };
class Descriptor {
public:
Descriptor(types type):
_type{type}
{}
types &type() { return _type; }
virtual ~Descriptor() = default;
private:
types _type;
};
class Number: public Descriptor {
public:
Number(types descType):
Descriptor(descType)
{}
virtual ~Number() = default;
int intValue;
};
void printValue(Descriptor t) {
auto cast = dynamic_cast<Number *>(&t);
if (cast == nullptr) {
std::cout << "Err" << std::endl;
} else {
std::cout << "Works" << std::endl;
}
}
int main() {
Number t = Number(INTEGER);
t.intValue = 1;
printValue(t);
}
The output is always Err. However when I change Number (in main) to be allocated on the heap with new the cast works and is able to access any functions within class Number?
Whats the difference in casting a stack object? When I tried to use static cast and access "intValue" it just gave me a garbage value. Is it possible to cast a stack object?