vidhu gangwar vidhu gangwar - 3 months ago 19
C++ Question

Invalid conversion from '`A**`' to '`void**`

#include <iostream>
using namespace std;

class A
{
public:
A(int x){ a = x;}
~A();
private:
int a;
};

int main()
{
A* a = new A(10);
void** p;
p = &a;
return 0;
}


After compiling with g++ (GCC) 4.1.2 20080704 , I am getting following error :


test.cpp: In function '
int main()
':

test.cpp:17: error: invalid conversion from '
A**
' to '
void**
'

Answer

You can't just assign the value of one type (A**) to the variable of another one (void**). You need to convert value from one type to another:

class A
{
    public:
        A(int x){ a = x;}
        ~A();
    private:
        int a;
};

int main()
{
    A* a = new A(10);
    void** p;

    // use `reinterpret_cast'
    p = reinterpret_cast<void**>(&a);

    // C-style cast also works but is a bad practice in C++
    p = (void**)&a;

    return 0;
}
Comments