Nogaz
Nogaz

Reputation: 29

cannot access private member declared in class

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'

Upvotes: 1

Views: 11589

Answers (4)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24153

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

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

};

Upvotes: 2

riv
riv

Reputation: 7323

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
{}

Upvotes: 7

Some programmer dude
Some programmer dude

Reputation: 409356

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.

Upvotes: 0

Mike Corcoran
Mike Corcoran

Reputation: 14565

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();
};

Upvotes: 5

Related Questions