Question

I don't get the difference between passing the instance of an object to passing a dereferenced object. I have

class A
{
public:
  A() {}

  void m() {}
};

void method(A& a)
{
  a.m();
}

int main(int argc,char** argv)
{
  method(A());
  return 0;
}

The call above does not work with compiler errors:

In function 'int main(int, char**)':
error:no matching function for call to 'method(A)'
note: candidates are:
note: void method(A&)
note: no known conversion for argument 1 from 'A' to 'A&'
note: void method(B&)
no known conversion for argument 1 from 'A' to 'B&'

But if I write

method(*(new A()));

it does.

Can anyone please tell my why and how to resolve the problem if I cannot change the method I want to call?

Was it helpful?

Solution 2

Here you are creating a temporary object:

method(A()); // A() here is creating a temporary
             //     ie an un-named object

You can only get const& to temporary objects.
So you have two options:

  1. Change the interface to take a const reference.
  2. Pass a real object.

So:

// Option 1: Change the interface
void method(A const& a)  // You can have a const
                         // reference to a temporary or
                         // a normal object.


// Options 2: Pass a real object
A a;
method(a); // a is an object.
           // So you can have a reference to it.
           // so it should work normally.

OTHER TIPS

In the first case, you create a temporary object that you try to pass to method.
A temporary object cannot be modified (it doesn't make sense to modify it, it will be gone the moment method returns). So to pass a temporary by reference, you must pass by a const reference.

void method(const A& a)
{

}

If this were legal, horrible things would happen. Consider:

void addOne(double& j) { ++j; }

int q = 10;
addOne(q);

This would create a temporary double, add one to it, and leave your original q unmodified. Ouch.

If method modifies its parameter, your code is broken. If it doesn't, it should take a const reference.

Problem that you see is that your function accepts only lvalue of type A. To solve the issue you can either change your function to accept type A by value:

void method( A a ) {}

or by const reference:

void method( const A &a ) {}

or by rvalue reference (if you use C++11):

void method( A &&a ) {}

or pass lvalue of type A to your method:

A a; method( a );

If you want to understand the problem deeper read about lvalue in c++

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top