I’m sorry to ask such a newbie question.
Here is my problem :
MyClass* c = new MyClass("test");
method(c);//error cannot convert MyClass* to MyClass
the definition :
method(MyClass c);
should I also define ?
method(MyClass* c);
I don’t want to duplicate the code, what is the proper way ?
You’re clearly a Java programmer! First of all, you will need to do:
Note that
cis a “pointer toMyClass” – this is necessary because thenewexpression gives you a pointer to the dynamically allocated object.Now, to pass this to a function that takes a
MyClassargument, you will need to dereference the pointer. That is, you will do:Note that because the function takes a
MyClassby value (not a reference), the object will be copied into your function. TheMyClassobject insidemethodwill be a copy of the object you allocated earlier. The type of the argument depends on exactly what you want your function to do and convey. If instead you want a reference to the object, so that modifying the object inside the function will modify thecobject outside the function, you need your function to take aMyClass&argument – a reference toMyClass.If you were to have the argument be of type
MyClass*, then you could simply do:This will give you similar semantics to passing a reference, because the pointer
cwill be copied into the function but the object that pointer refers to will still be the dynamically allocatedMyClassobject. That is, if inside the function you modify*d, the object pointed to bycis also modified.Passing a raw pointer like this is usually not a very good approach. The function will have to explicitly check that the pointer is not null, otherwise your program may crash under certain conditions. If you want pass-by-reference semantics, use reference types – it’s what they’re for.
However, you’re better off not dynamically allocating your
MyClassobject in the first place. I guess you’re only usingnewbecause you did it a lot in Java. In C++, thenewexpression is used to dynamically allocate an object. More often than not, you do not want to dynamically allocate an object. It is perfectly fine to create it with automatic storage duration, which you would do like so:It is considered very good practise in C++ to avoid pointers and dynamic allocation unless you have a good reason. It will only lead you to more complicated code with more room for errors and bugs. In fact, the code you’ve given already has a problem because you didn’t
delete c;. When you do as I have just suggested, you don’t need to explicitly delete anything, because the object will be destroyed when it goes out of scope.