1

this is my first question in here :) i have i little problem.. these are my classes:

class Gracz{
    char znak_gracza;
public:
    Gracz();
    Gracz(char znak){
            this->znak_gracza = znak;
        };
    friend void multiplayer();
};
class Osoba: public Gracz{
public:
    Osoba();
    Osoba(char znak){
            this->znak_gracza = znak;
        };
    friend void multiplayer();
};

i also have a function multiplayer, where i try tu use constructor with argument:

void multiplayer(){
    Osoba gracz1('O');
    Osoba gracz2('X');
...
}

but it doesn't work.

errors are same for gracz1 and gracz2

error C2248: 'Gracz::znak_gracza' : cannot access private member declared in class 'Gracz'
see declaration of 'Gracz::znak_gracza'
see declaration of 'Gracz'
dwalter
  • 7,258
  • 1
  • 32
  • 34
Nogaz
  • 29
  • 1
  • 1
  • 6

4 Answers4

7

Derived classes cannot access private members of a parent class. You can declare them as protected (which is like private but lets derived classes access it), but in your case, since Gracz provides a way to initialize the variable, you should just let Osoba pass the argument to Gracz constructor.

Osoba(char znak)
    : Gracz(znak) // initializes parent class
{}
riv
  • 6,846
  • 2
  • 34
  • 63
5

private member access is only available to members of the class, and friends. what you're looking for it to declare char znak_gracza as protected, so classes that inherit Gracz have access to that member as well.

your class Gracz should look more like this:

class Gracz{
protected:
    char znak_gracza;
public:
    Gracz();
    Gracz(char znak){
            this->znak_gracza = znak;
        };
    friend void multiplayer();
};
Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49
2

The constructor needs to pass the parameter to the base class constructor:

class Osoba: public Gracz{
public:
    //...
    Osoba(char znak) :
    Gracz(znak) {
    }

};

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

The multiplayer function is a friend of the Gracz class, but the Osoba class isn't.

Remember that child classes can't automatically access parent classes private variables. If you want Osoba to access the znak_gracza variable you have to make it protected.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621