Question

I have a base class:

class Base
{
public:
    functions...
private:
    std::vector<float> privateElement;
}

and a derived one:

class Derived : public Base
{
public:
    functions...
    Derived(anotherElement) : privateElement(anotherElement)
    {

    }
}

My problem now is that everytime I try to build my project, the compiler (gcc 4.7.2) always complains about not being able to access privateElement, like:

class Derived does not have any field named privateElement
std::vector<float> Base::privateElement is private

May anybody help me here?

Was it helpful?

Solution

First of all, private members of base class are not accessible from derived class.

Now even if you fix that and make it protected (or public), then this will still be ill-formed, because you cannot initialize the base's members in the derived class's mem-init-list. It doesn't make sense, because by the time the derived class mem-init-list executes the base's members are already initialized, and the syntax : protectedElement(xyz) will make the compiler think that protectedElement is a member of the derived class, not of the base class!

See this error even after making it protected:

main.cpp: In constructor ‘Derived::Derived(std::vector<float>)’:
main.cpp:20:37: error: class ‘Derived’ does not have any field named ‘protectedElement’
     Derived(std::vector<float> v) : protectedElement(v)
                                     ^

Online demo

The right way to do this is to define a constructor for the base class, and call this from the derived class initialization-list.

Hope that helps.

OTHER TIPS

The right way to do it without breaking encapsulation would be for the base class to provide a constructor which we can call from derived class :

class Derived : public Base
{
public:
    functions...
    Derived(anotherElement) : Base(anotherElement)
    {

    }
}

class Base
{
public:
    Base(anotherElement):privateElement(anotherElement) { }
private:
    std::vector<float> privateElement;
}

Derived class cannot access private parts of the base class. That's because they are, well, private. Use protected if you want the derived class to have access to the base class' members without breaking the encapsulation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top