Object pointers to any type

https://stackoverflow.com/questions/2834139/declaring-a-data-type-dynamically-in-c/2834157#2834157


The question is how in c++ we can have a pointer that points to anything:

In c# (not c++) object is the base for all reference types. There also is a relevant concept about boxing and unboxing.

Anyway, you can assign any instance of any type to an instance of an object class.

For example:

c#

bool b=true;

int i=45;

object obj=i;

obj=b;


Despite many that say in c++ it's not possible … during my research I noticed that it looks c++ has a robust mechanism that is very reliable for it, but lack of time did not allow me to go more trough that solution.


Anyway, I have made my own simplified dummy solution for it:


C++ code

#include <iostream>

void pointerInfo(auto *objectPointer)

{

    std::cout << "address of object is: " << objectPointer << "\t"

              << "type of the object is: " << typeid(*objectPointer).name() << "\t"

              << "value of object is: " << (*objectPointer) << "\t"

              << "sizeof pointer is: " << (sizeof(objectPointer)) << "\t"

              << "size of object: " << (sizeof(*objectPointer)) << "\n\n";

}

main()

{

    int i = 345;

    pointerInfo(&i);

    bool b = true;

    pointerInfo(&b);

    double d = 23.44;

    pointerInfo(&d);

    // now its time to take a dynamic pointer that can pint to anything , luckily size of (long long) is 8 and it can hold an address";

    long long address;

    std::cout << "\ndynamic object\n\n";

    address = (long long)&i;

    pointerInfo((int *)address); // in the action you have to say interpret as what (int) but if you want more dynamic without mentioning interpretation information again you have to implement however i guess there are something builtin as well in c++

    address = (long long)&b;

    pointerInfo((bool *)address);

    address = (long long)&d;

    pointerInfo((double *)address);

}



Also have a look at https://www.geeksforgeeks.org/void-pointer-c-cpp/

based on that, you don't even need (long long) to store an address, and it can be stored in (void* (or even any pointer (any*/int* ….)))