I'm writing a C++ program where I have two derived objects from a base class, say, Derived_1 & Derived_2.
During processing, the first object adjusts the base data member (just simulating that using the Derived_1's default constructor here). What I'd like to do is then read that data from the Derived_1 object and use it during Derived_2's constructor to initialize that same member in Derived_2.
// -std=c++14
#include <iostream>
class Base {
public:
int data(void) { return data_; }
protected:
int data_{0};
};
class Derived_1 : public Base {
public:
Derived_1(void) { this->data_ = 42; }
};
class Derived_2 : public Base {
public:
// Derived_2(const Derived_1& a1) { this->data_ = a1.data_; }
};
int main() {
Derived_1 a1;
std::cout << "Derived_1 data: " << a1.data() << '\n';
// Derived_2 a2 = a1;
// std::cout << "Derived_2 data: " << a2.data() << '\n';
}
If the constructor in Derived_2 is uncommented, this error occurs:
In constructor ‘Derived_2::Derived_2(const Derived_1&)’:
error: ‘int Base::data_’ is protected within this context
Derived_2(const Derived_1& a1) { this->data_ = a1.data_; }
^~~~~
I've looked through a number of related questions here on SO trying to find a solution, (for example) Access a derived private member function from a base class pointer to a derived object and Why can I access a derived private member function via a base class pointer to a derived object? but I'm currently having real difficulty spotting the answer if I've seen it. Probably just my inexperience.
Thanks for helping clear this up for me.