Search code examples
c++derived-class

Derived class using variables from abstract base class C++


I created an abstract Light class with fields and methods common for all the lights and now I try to derive a Directional Light from it.

class Light
{
public:
    unsigned int strength;
    Color color;
    unsigned int index;

    Light() {};
    virtual ~Light() = 0;

    virtual pointLuminosity() = 0;
};

class DirectionalLight : public Light
{
public:
    Vector direction;
    DirectionalLight(const unsigned int &_strength, [...] ): strength(_strength), [...] {}
};

The above code results in an error:

error: class 'DirectionalLight' does not have any field named 'strength'

What is the proper way to derive all the fields from Light class and use them in the DirectionalLight objects?


Solution

  • You can use strength anywhere but an initialiser list. This works

    DirectionalLight(const unsigned int &_strength) { strength = _strength; }
    

    Alternatively you can add a constructor to Light

    class Light
    {
    public:
        unsigned int strength;
        Light(unsigned s) : strength(s) {}
    };
    
    DirectionalLight(const unsigned int &_strength) : Light(_strength) {}