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;};