I am writing a universal data type (mini version) The problem arose when calling getInside();

Conclusion: Integer val: -858993460 Why is that? And how to fix it?

 class AnyType { private: int *integer; double *floating; bool *boolean; public: AnyType() { integer = nullptr; floating = nullptr; boolean = nullptr; } template<typename T> AnyType(T val) { if (typeid(floating) == typeid(T*)) { floating = &val; } } void ToInt() { int tmp=int(*floating); integer = &tmp; } void getInside() { cout << "Integer val:" << *integer << endl; } }; int main() { AnyType fff(1.5); fff.ToInt(); fff.getInside(); system("pause"); return 0; } 
  • I do not see anything universal - AR Hovsepyan

2 answers 2

Error here:

 void ToInt() { int tmp=int(*floating); integer = &tmp; } 

The variable tmp local to the ToInt method, so it is placed on the stack. The integer pointer points to the address tmp inside the stack. When the execution of ToInt completed, you call getInside , and it, in turn, calls the methods cout::operator << to output a string and a number.

These methods place their variables on the stack, overwriting the tmp value that you put there.

To solve your problem in C and C ++ use the constructor type union , union .

An alternative solution that is suitable for an object-oriented language is the abstract base class Variable and heirs of the types IntVariable , DoubleVariable , and so on.

The solution with pointers is difficult for such a task.

    The floating variable will contain a pointer to local variables val tmp that go out of scope making the pointer invalid. Accordingly, it is necessary to assign a pointer to the address of a variable allocated on the heap or some internal buffer.

    • @ VTT.To, I need to copy the value of val , in the constructor into a buffer variable of the same type, and then pass the reference to the buffer in floating ? - Awesome Man
    • I did so. Before checking the type: T atas= val; and in the floating = &atas; type check floating = &atas; But it did not help. - Awesome Man
    • one
      @AwesomeMan If you write T atas= val; before checking the type, or in checking the type, or anywhere inside the method and then doing floating = &atas; , the pointer will still point to a local variable that immediately goes out of scope. - VTT
    • Thanks, I just did not immediately understand your answer. - Awesome Man