Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid conversion from ‘const type*’ to ‘type*’

I want to store through the constructor of a class a pointer to an object of another class. What is the correct way to do that?

If I substitute MyClass1* ptr with const MyClass1* ptr there is no error, but in this case I think that i cannot change ptr anymore. What is the correct way to achieve what i want?

example.cpp

class MyClass1{
    public:
        int a;
        int b;
};

class MyClass2{
    MyClass1* ptr;
    public:
        MyClass2(const MyClass1& obj){ptr = &obj;};
};

int main(int argc, char* argv[]){
    MyClass1 object1;
    object1.a = object1.b = 0;
    MyClass2 object2(object1);
    
    return 0;
}

Compile it through g++ -o example example.cpp give me this error

example.cpp: In constructor ‘MyClass2::MyClass2(const MyClass1&)’:

example.cpp:10:37: error: invalid conversion from ‘const MyClass1*’ to ‘MyClass1*’ [-fpermissive]

MyClass2(const MyClass1& obj){ptr = &obj;};

like image 662
gvgramazio Avatar asked Oct 21 '15 13:10

gvgramazio


3 Answers

If you want to change the thing that ptr points to, then your function needs to take its argument by non-const reference (since MyClass2 might modify it):

MyClass2(MyClass1& obj) { ptr = &obj; }

Or, if you don't intend to modify the thing that ptr points to, then ptr should be declared as a pointer-to-const:

const MyClass1* ptr;

Both of these solutions will cause the code to compile.

like image 191
emlai Avatar answered Nov 13 '22 11:11

emlai


Answering based on the last few comments.

I'll give you an example of const applied to pointers with ints,

int a = 2;
int b = 3;

int*              p1 = &a; // Modifiable pointer  modifiable value
const int*        p2 = &a; // Modifiable pointer  const value
int* const        p3 = &a; // Const pointer       modifiable value
const int * const p4 = &a; // Const pointer       const value

*p1 = 3; // Ok, modifiable left-value
*p2 = 4; // Error: non-modifiable left-value
*p3 = 5; // Ok
*p4 = 6; // Error

p1 = &b; // Ok: modifiable pointer
p2 = &b; // Ok
p3 = &b; // Error
p4 = &b; // Error

In your case, you're looking for a modifiable pointer but a const value. So you want the second case,

const MyClass1* ptr;

(Which is what you originally had)

It would seem you didn't actually try to change the pointer?

like image 22
aslg Avatar answered Nov 13 '22 10:11

aslg


I known from the comment that you want to modify the content of pointer, not the object pointer points to, so please declare the ptr pointer as const MyClass1* ptr. This means that ptr is a pointer which refers to a const MyClass1. So you can change the pointer, but you are not able to modify the object referenced by the pointer.

like image 2
Jack47 Avatar answered Nov 13 '22 10:11

Jack47