Sign in to follow this  
Finalspace

Why does my c++ compiler does not like methods in structs in combination with const reference ?

Recommended Posts

Why does my c++ compiler does not like methods in structs in combination with const reference? I get the follow error, even though i marked that function as "const":


E1086    the object has type qualifiers that are not compatible with the member function "ButtonState::WasPressed"
C2662    "bool ButtonState::WasPressed(void)": this-Pointer cannot be converted from "const ButtonState" to "ButtonState &"

		struct ButtonState {
			b32 isDown;
			s32 halfTransitionCount;

			inline bool WasPressed() { const
				bool result = ((halfTransitionCount > 1) || ((halfTransitionCount == 1) && (isDown)));
				return(result);
			}
		};

		struct Controller {
			u32 playerIndex;
			union {
				struct {
					ButtonState moveUp;
					ButtonState moveDown;
					ButtonState moveLeft;
					ButtonState moveRight;
				};
				ButtonState buttons[4];
			};
		};

		struct Input {
			f32 deltaTime;
			union {
				struct {
					Controller keyboard;
				};
				Controller controller[1];
			};
			u32 playerOneControllerIndex;
		};

void handleInput(const Input &input) {
	const Controller &playerController = input.controller[input.playerOneControllerIndex];
  	if (playerController.moveUp.WasPressed()) { // <- compile error here
      // Stuff
    }
}

 

Share this post


Link to post
Share on other sites
7 minutes ago, Finalspace said:

inline bool WasPressed() { const

The `const' should go before the curly bracket. The way you wrote it, the `const' is modifying the next variable (`const bool ...').

And I don't think you should be using `inline' there (it most likely has no effect, so your code is cleaner if you remove it).

Share this post


Link to post
Share on other sites
inline bool WasPressed() { const
	bool result = ((halfTransitionCount > 1) || ((halfTransitionCount == 1) && (isDown)));
	return(result);
}

You misplaced the const keyword. You have to place it immediately after WasPressed(). With your code, the compiler interprets that the const is related to the bool "result".

Edited by Aerdna

Share this post


Link to post
Share on other sites

Something that I saw too.

This kind of 'mistake' can show a coding style which does not suit best the user. Sometimes the coding style is not just an aesthetic thing. But it can also be something to help avoid writing mistakes :)

I also put braces at the same line, but for loops and conditions, not for class or function/method definitions.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this