cannot access private member declared in class 'Soldier'

25,797

Solution 1

People have already answered this now, but explicitly:

class Soldier
{
private:
    int health;
    int strength;

public:
    Soldier(int SetHealth, int SetStrength);

    void attacked();
    void healed();
    int getHealth();
    int getStrength();
};

BTW What are attached and healed going to do? They take no parameters and return nothing. Odd.


Edit (in light of recent down vote):

Moving the constructor to the public "section", makes it public. Things start off as private until you say otherwise.

Solution 2

Your constructor is private (just as the error message says). By default, every member of a Class is private if you don't specify an access level.

Solution 3

The constructor that you have defined has a access level of

private

By default if one does not mention anything, the access level is private So change it to public for access.

Solution 4

A class's members are implicitly private unless you change the access level to public or protected, so Soldier::Soldier(int SetHealth, int SetStrength); is private - ergo you can't access it.

Share:
25,797
Admin
Author by

Admin

Updated on February 01, 2020

Comments

  • Admin
    Admin over 4 years

    I'm new to OOP and I do not understand how to pass arguments to classes.

    The class' declaration:

    class Soldier
    {
        Soldier(int SetHealth, int SetStrength);
    
    private:
        int health;
        int strength;
    
    public:
        void attacked();
        void healed();
        int getHealth();
        int getStrength();
    };
    

    Definition of the constructor:

        Soldier::Soldier(int SetHealth, int SetStrength):
            health(SetHealth),
            strength(SetStrength)
        {
    
        }
    

    When I try passing arguments to the class it says this:

        1>------ Build started: Project: ConsoleApplication6, Configuration: Debug Win32 ------
        1>  ConsoleApplication6.cpp
        1>c:\users\user\documents\visual studio 2012\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp(11): error C2248: 'Soldier::Soldier' : cannot access private member declared in class 'Soldier'
        1>          c:\users\user\documents\visual studio 2012\projects\consoleapplication6\consoleapplication6\soldier.h(7) : see declaration of 'Soldier::Soldier'
        1>          c:\users\user\documents\visual studio 2012\projects\consoleapplication6\consoleapplication6\soldier.h(6) : see declaration of 'Soldier'
        ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========