Scratch Cat
Scratch Cat

Reputation: 59

Having issue using inherited protected member (C++)

Here is the issue I'm having. Here is my Soldier class:

#ifndef SOLDIER_H
#define SOLDIER_H

#include <iostream>

class Soldier{
protected:
    const int m_damage;
public:
    Soldier():
        m_damage(5)
    {}
};

#endif // SOLDIER_H

And here is my Warrior class, inheriting from it :

#ifndef WARRIOR_H
#define WARRIOR_H

#include "Soldier.h"

class Warrior: public Soldier{
public:
    Warrior():
        m_damage(10)
    {}
};

#endif // WARRIOR_H

The problem is when I run the program, I get this error :

Warrior.h: In constructor 'Warrior::Warrior()':
Warrior.h:9:9: error: class 'Warrior' does not have any field named 'm_damage'
         m_damage(10)

It seems that, although I set

const int m_damage;

As protected in the Soldier class and publicly inherited it in the Warrior class, I still cannot access it. Any help would be much appreciated.

Upvotes: 0

Views: 46

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21609

It is true Warrior has no member m_damage. It belongs to Soldier and only Soldier can initialize it.

You should allow Soldiers constructor to take the damage parameter as an argument and pass the value you want for m_damage to it when constructing base classes.

#include <iostream>

class Soldier{
protected:
    const int m_damage;
public:
    // explicit will prevent implicit conversions from 
    // being permitted when constructing Soldier
    // see http://en.cppreference.com/w/cpp/language/explicit
    explicit Soldier(int damage=5):
        m_damage(damage)
    {}

    int damage() const
    {
        return m_damage;
    }
};

class Warrior: public Soldier{
public:
    Warrior()
        :  Soldier(10)
    {}
};

// lets make another subclass which implicitly uses the 
// default Soldier constructor.
class Samurai: public Soldier{
public:
    Samurai()
    {}
};

int main(){
    Warrior w;
    Samurai s;

    std::cout << w.damage() << '\n';
    std::cout << s.damage() << '\n';
}

Upvotes: 3

Related Questions