Richard Taylor
Richard Taylor

Reputation: 2752

Pointer confusion

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?

Upvotes: 0

Views: 178

Answers (2)

parapura rajkumar
parapura rajkumar

Reputation: 24413

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++

Upvotes: 10

Timo Geusch
Timo Geusch

Reputation: 24351

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.

Upvotes: 4

Related Questions