views:

155

answers:

6

I have a constructor attempting to initialize a field in a base class. The compiler complains. The field is protected, so derived classes should have access.

//The base class: 

class BaseClass

{

public:

    BaseClass(std::string);
    BaseClass(const BaseClass& orig);
    virtual ~BaseClass();
    const std::string GetData() const;
    void SetData(const std::string& data);
protected:

    BaseClass();
    std::string m_data;

};

BaseClass::BaseClass(const std::string data) : m_data(data) { }

BaseClass::BaseClass() { } 

BaseClass::BaseClass(const BaseClass& orig) { }

BaseClass::~BaseClass() { }

void BaseClass::SetData(const std::string& data)
{
    m_data = data;
}

const std::string BaseClass::GetData() const
{
    return m_data;
}


//The derived class: 


class DerivedClass : public BaseClass
{

public:

    DerivedClass(std::string data);
    DerivedClass(const DerivedClass& orig);
    virtual ~DerivedClass();
private:

};

DerivedClass::DerivedClass(std::string data) : m_data(data) { } //ERROR HERE

DerivedClass::DerivedClass(const DerivedClass& orig) { }

DerivedClass::~DerivedClass() { }

//The compiler error

DerivedClass.cpp:3: error: class ‘DerivedClass’ does not have any field named ‘m_data’

Any help is greatly appreciated. Thank you in advance.

+4  A: 

You cannot initialize m_data in the derived class constructor but instead pass it as an argument to the base class constructor.

That is: DerivedClass::DerivedClass(std::string data) : BaseClass(data) { }

Zitrax
+1. It's stronger than *should not*. It is actually *cannot*.
JaredPar
True I updated answer.
Zitrax
That it, thank you!
A: 

Initializer lists can only be used to initialize fields which are owned by the type in question. It is not legal to initialize base class fields in an initializer lists which is why you receive this error. The field is otherwise accessible within DerivedClass

JaredPar
+1  A: 

In the initializer list you can just set values for atributes of the same class. To access it you must attribute the value in the body of the constructor:

DerivedClass::DerivedClass(std::string data) {m_data = data; }

Or, if it is expensive to copy the object, you pass the m_data as an argument to the parent class constructor:

DerivedClass::DerivedClass(std::string data) : BaseClass(data) {}

See more info here: order of initialization of C++ constructors.

neves
A: 

You are not "accessing" m_data -- you are initializing it. However, it's already been initialized in the Base Class's ctor. If you want to change it's value, assign to it in the body of your ctor:

DerivedClass::DerivedClass(std::string data) 
{
   m_data = data;
}
James Curran
A: 
Will Manley
A: 

You need to call the base class constructor as follows:

DerivedClass::DerivedClass(std::string data) : BaseClass(data) {
}

Each class should be in charge of initializing it's members.

code-gijoe