Im calling a method foo
by const ref
:
// method, which is being called
void foo(const Entity & ent);
// call
Entity* e = new Entity;
foo(e); // wrong: missing * but compiles
This piece of code does not only compile, it creates a new instance of Entity
with its default values in the scope of foo
. I'd expect that this does not compile or at least crashes.
If I call foo
correctly (foo(*e)
), everything works as suspected and I see the right values of Entity
within foo
.
Im using mingw supplied with Qt 4.7.
Here's the interface of Entity
:
class Entity : public QObject
{
Q_OBJECT
public:
Entity (QObject* parent = NULL);
long getId() const { return this->id; }
void setId(const long id) { this->id = id; }
QString getName() const { return this->name; }
void setName(const QString & name) {this->name = name; }
private:
QString name;
long id;
};
The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.
Example - Call By ReferenceIt creates a copy of references and passes them as valuable to the methods. As reference points to same address of object, creating a copy of reference is of no harm. But if new object is assigned to reference it will not be reflected.
It is a way of passing arguments to a function call in which both the actual argument and formal parameters refer to the same memory locations and any changes made within the function are reflected in the actual parameters of the function when called.
[Edited] You have an implicit converting constructor (that also happens to be a default constructor) from Entity*
(via parent QObject*
) to Entity
and it's being used to create a temporary instance to pass in.
For this reason I always suggest by default making all single-parameter callable constructors (for example where all but one parameter is defaulted) explicit and avoiding implicit conversion operators except when they exactly perform the conversion semantics that would be expected in all circumstances. In other cases make the conversions available through explicit methods.
There are occasionally cases where implicit conversions are useful, and each one should be evaluated on a case-by-case basis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With