0

I am fairly novice at C++, and I'm having an error that I just don't understand.

class1* a = (class1*)p1;
class2* b = (class2*)p2;
a->foo(b);

The error is:

error: no matching function for call to 'a::foo(b*&)'
note: candidates are: void a::foo(const b&)

How do I get this right?

Richard Taylor
  • 2,702
  • 2
  • 22
  • 44
  • It's obvious from the error message that the code you showed us is not the same code you tried to compile. In the future, show us your *actual* code, not a from-memory approximation. – ildjarn May 31 '11 at 21:53
  • 1
    @ildjam: I would actually think that the error message is quite related to the code presented: trying to call a method `foo` of the class `a` using as argument an lvalue of type `b*`, which matches `a->foo( b )` perfectly. – David Rodríguez - dribeas May 31 '11 at 22:20
  • 1
    @dribeas: except that somewhere between the real code and this question, the type `a` has been renamed to `class1` and `b` to `class2`, then the variables named after the old type names. – Steve Jessop May 31 '11 at 22:32
  • This is copied directly, and variables renamed (because they're long, ugly, and distract from the point) - thanks to those who helped! – Richard Taylor Jun 01 '11 at 14:28

2 Answers2

10

You probably have to do

  a->foo(*b);

because foo takes a reference to b not a pointer to b.

What are the differences between a pointer variable and a reference variable in C++? is a good place to learn the difference between a pointer and a reference in C++

Community
  • 1
  • 1
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • 4
    @Sticky: Do you understand the difference between references, pointers and address of objects? – Klaim May 31 '11 at 21:59
4

You're calling a function that expects a reference to an object with a pointer to said object (which is an incompatible type). To get the code to compile, you want to call foo like this:

a->foo(*b);

Essentially you're dereferencing the pointer to get the actual object and pass that one to foo. The compiler takes care of passing a reference to the object instead of the object itself.

Timo Geusch
  • 24,095
  • 5
  • 52
  • 70