Poperton
Poperton

Reputation: 1808

Setting protected member of base class in child class

Since I maked x as protected, shouldn't class B inherit x from A?

class A {
    public: 
    A() {

    }
    protected:
    int x = 0;
};

class B: public A{
    B():x(1){

    }
};

int main()
{
    B b;
}

I'm getting that x does not exist on B

Upvotes: 0

Views: 57

Answers (3)

Ezaren
Ezaren

Reputation: 23

Inherited member variables cannot be set in the initializer list of the constructor. You can either initialize it after your brackets, or do something like this:

class A {
public:
    A(int x) : x(x) {

    }
protected:
    int x = 0;
};

class B : public A {
public:
    B() : A(1) {

    }
};

int main()
{
    B b;
    return 0;
}

Upvotes: 1

tdao
tdao

Reputation: 17713

Since I maked x as protected, shouldn't class B inherit x from A?

Yes, it does. You can use it inside B constructor or any B member functions, eg

B() { x = 2; }  // ok

I'm getting that x does not exist on B

However, you can't initialise x in the initialisation list. So thing like this won't work:

B():x{1}  // no

You can only initialise x it A constructor where it is a member variable.

Upvotes: 0

eerorika
eerorika

Reputation: 238491

Since I maked x as protected, shouldn't class B inherit x from A?

Protected doesn't mean that the member is "inherited". A base is inherited, and the base contains all of its members (including the private ones). Protected access specifier means that the derived class has access to the name.

A base can only be initialised with a constructor of base. Members of a base cannot be initialised separately from it. Following would be correct:

struct B {
    B(int x) : x(x) {}
protected:
    int x = 0;
};

struct D : B{
    D() : B(1) {}
};

Upvotes: 0

Related Questions