Search code examples
c++classoopconstructorprivate

cannot access private member declared in class 'Soldier'


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 ==========

Solution

  • 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.

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