Pointers and C ++ objects


I'm having a hard time with * and & in the following code:

Declare variable and call function:

SDL_Event event;


void MyApp::myfunc(SDL_Event* event) {
    while ( SDL_PollEvent(&event) ) {
        if (event.type == SDL_QUIT) {
            // ...

Compiler: error: no matching function for call to 'MyApp::myfunc(SDL_Event&)' note: candidates are: void MyApp::myfunc(SDL_Event*)|

What am I doing wrong and how can it be fixed?

First error: pointers and objects

You need to call myfunc with a pointer to a SLD_Event object, instead of calling with the SLD_Event object itself:


Putting a & in front of a object (or variable) tells the compiler that you want the memory address of the object (which is the so called pointer to it).

Putting a * in front of a pointer to an object tells the compiler that you want the content of the memory address to which the pointer points (which is the object or variable itself)

The compiler error you get, tells that the compiler is not able to find a function with the name myfunc that accepts a (reference to) an SLD_Event object. Which is correct since the (only) myfunc function available requires a pointer to a SLD_Event object as its argument.

Second error: pointers to pointers

The second (independent to the first one) compiler error (error: cannot convert 'SDL_Event**' to 'SDL_Event*' for argument '1' to 'int SDL_PollEvent(SDL_Event*)') you got, tells that the variable type you put into the SLD_PollEvent function is incompatible with the expected typeand it could not be converted automatically.

Because you added a & before the event variable in that function call, you are basically asking to get the pointer to the memory location which points the the event object. The is perfectly legal C code, but not what you want, because the SLD_EventPoll function expect the pointer the the event object (which has the type SLD_Event *).

So to solve your second error change the line into:

while ( SDL_PollEvent(event) ) {

(notice the removed &)

Third error: Addressing object variables in (pointers to) objects

The third error in your code is the event.type. Because event is a pointer the the SLD_Event object, C++ expects a -> instead of the . (which is used for objects, ie SLD_Event without the *).