Tarupron
Tarupron

Reputation: 548

C++ Default Values

It pains me so bad to ask this question, I know the answer but I'm just completely blanking on it.

What my program is, is a simple program that displays damage. All I need is to be able to call my classes enemy and boss with the function attack. So basically enemy.Attack() or be able to call like this enemy.Attack(30) and have the output look different.

Here's what needs to happen:

enemy.Attack() Output: 10

enemy.Attack(30) Output: 30

Every time I attempt the empty bracket version, I get the error "function does not take 0 arguments"

Enemy.h

class Enemy
{
public:
    Enemy();
    void Attack();

private:
    int m_Damage;
};

Enemy.cpp

#include <iostream>

#include "enemy.h"

Enemy::Enemy() : m_Damage(10)
{}

void Enemy::Attack(int damage)
{
m_Damage = damage;
std::cout << "Damage: " << m_Damage << std::endl;
}

Upvotes: 2

Views: 129

Answers (1)

WhozCraig
WhozCraig

Reputation: 66254

Provide default arguments in your class member declaration:

class Enemy
{
public:
    Enemy();
    void Attack(int damage = 10);

private:
    int m_Damage;
};

The remainder of your implementation can stay as-is (though I would default-construct m_Damage to zero myself, or not even use it, as I'm not sure you need it at this point).

Upvotes: 6

Related Questions