Invalid conversion from 'const type * to' type *

I want to save a pointer to an object of another class through the constructor of the class. What is the right way to do this?

If I replace MyClass1* ptr with const MyClass1* ptr , there is no error, but in this case, I think I can no longer change ptr . What is the right 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 with g++ -o example example.cpp to inform me of this error

example.cpp: In the constructor of MyClass2 :: MyClass2 (const MyClass1 &):

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

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

+5
source share
4 answers

If you want to change what ptr points to, then your function should take its argument using the < const reference (since MyClass2 can change it):

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

Or, if you do not intend to change what ptr points to, then ptr should be declared as a pointer to < const :

 const MyClass1* ptr; 

Both of these solutions will lead to compilation of the code.

+2
source

Answer to the last few comments.

I will 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 are looking for a mutable pointer, but a const value. So you want a second case,

 const MyClass1* ptr; 

(This is what you originally had)

It would seem that you were not really trying to change the pointer?

+2
source

I know from the comment that you want to change the contents of the pointer, not the pointer to the object, so please declare the ptr as const MyClass1* ptr . This means that ptr is a pointer that refers to const MyClass1 . That way you can change the pointer, but you cannot change the object that the pointer refers to.

+2
source

First remove the excess;

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

can't pass const argument inside const argument (can change it later), so this might work:

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

but here the value & obj goes beyond the local area.

0
source

Source: https://habr.com/ru/post/1234199/


All Articles