Conversion from 'monster*' to non-scalar type 'monster' requested

class monster {
    int HP = 100;
    void hit(int DMG) {
      HP -= DMG;
    }
};

void setup() {

}

void loop() {
  monster m = new monster();
  m.hit();
}

I'm trying to make a 'monster' class for a game, but it keeps returning this error:
conversion from 'monster*' to non-scalar type 'monster' requested

I am using an Arduino Uno R3

Don't ask me why (I'm a C programmer, not a C++ programmer) but get rid of the new keyword.

Your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advise on) your project :wink: See About the Installation & Troubleshooting category.

new returns a POINTER to the new object.

monster *m = new monster();

creates a new monster object on the heap, and sets the pointer m to point to it. If you do this within loop(), you MUST delete it before exiting loop, or the heap memory occupied by the object will be lost, and you WILL run out of memory very quickly.

monster m;

creates a new monster object named m on the stack. If this is done within any function, the object will be discarded when the function exits, unless the object is declared static.

1 Like

Thanks, that is what I was missing. :+1:

I should actually have know :frowning:

You don't need the '()':

monster *m = new monster;

No it doesn't. But, this does:

monster m;

And, if used out side of any function it will make a global monster instance named 'm'.

BTW, other problems with this minimal code:

  • By convention the name of the class should be capitalized: 'Monster'
  • All members of the monster class are private. It won't be very useful.
  • Syntax for accessing the hit() function (if it were public) via the pointer is:
m->hit();

.... except that doesn't supply the 'int' argument that the function expects per the class declaration.

1 Like

It's what happens when you type too late at night... Well, at least it happens to me! :slight_smile:

Post has been updated.

Thank you for the other errors I neglected to fix, and how exactly do I make a class function public?

Place

public:

before the definitions of any member data or functions you want to be public.

Place

private:

before the definitions of any member data or functions you want to be private.

For a class, all are private by default. For a struct, all are public by default. Using the modifiers above, you can force any or all members in classes or structs to whatever access you want.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.