about void pointer

how can i add the variable adress to a void pointer inside of a class?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class variant2
    {
    private:
        void *Vvariant=NULL;
    public:
        template<typename b>
        variant & operator = (b *adress)
        {
            Vvariant=adress;//add the adress of adress to Vvariant pointer
            return this;
        }

        friend ostream& operator <<(ostream &os,const variant2 &obj)
        {
            os << obj.Vvariant;
            return os;
        }
    };

if possible i want avoid the '&' when i assign the variable adress.(variant2 f=varname;//like you see i don't use the '&')
for the moment i just need put the address to Vvariant pointer. but i recive several errors :(
I'm a little confused by your question. Adding two pointers doesn't make any sense.

If you're asking how to assign one pointer to another, then you're already doing it properly. Only problem I see is that you are returning this instead of *this.

As for avoiding syntax -- language works by following syntax. If you want the address of something, you must use '&' at some point.
see these code:

1
2
3
int a=100;
void *b=&a;
cout << *static_cast<char*>(b);

why i recive only 1 character(like a ascii table code) instead 100 in string("100")?
Because a char is not a string.

And because integers are not stored in memory as strings.

Casting a void pointer is like doing a reinterpret_cast. That is... it's looking at that area in memory and reinterpretting the binary data as if it were some other type.

Assuming you have 32-bit integers and are on a little endian system... the integer 100 is stored in memory like so:

64 00 00 00

That's 4 bytes, with the low byte stored first (100 == 0x00000064)

In a completely unrelated happenstance... the ASCII code for the letter 'd' is also assigned a value of 100 (0x64). You can test this for yourself:

 
if( 'd' == 100 ) { /* this code will execute*/ }


So when you have a pointer that's looking at memory containing 64 00 00 00, and you tell it "hey... reinterpret that data as if it were a bunch of chars"... it's going to do exactly that.

64 00 00 00
becomes "d\0\0\0" (the letter 'd' followed by 3 null characters)
Because "d\0\0\0" is ALSO stored in memory as 64 00 00 00




So yeah... using void pointers and casting around C++'s type system is not a good idea unless you know what you're doing. And even if you do know what you're doing, it's still ill advised.
Topic archived. No new replies allowed.