-1

I'm having trouble understanding how to have a child class use a protected member from a parent class.

Suppose that in the parent class, I have a function, in public, that will set data_parent, a protected member, equal to some value.

Now, in the child class, I have a protected member called data_child and have a function, in public, that will return data_parent + data_child.

But, when I try to compile I receive the error " use of undeclared identifier 'data_parent' ". What am I doing wrong?

2 Answers2

3

I can't explain your error message, except that your code differs somehow from your description.

The following is essentially what you have described except that I added constructors (which are optional), picked names for the member functions, and added a driver program to test. It works without error.

#include <iostream>

class Parent
{
    public:
       Parent() : data_parent(0) {};
       void SetDataParent(int x) {data_parent = x;};
    protected:
        int data_parent;
};

class Child: public Parent
{
    public:
       Child() : Parent(), data_child(0) {};
       void SetDataChild(int x) {data_child = x;};
       int GetSum() const {return data_child + data_parent;};
    protected:
        int data_child;
};

int main()
{
    Child child;
    child.SetDataParent(42);
    child.SetDataChild(100);
    std::cout << child.GetSum() << '\n';
}

My guess is that you forgot to have Child inherit from Parent, making for a fairly tense family relationship.

Peter
  • 35,646
  • 4
  • 32
  • 74
0

Solved the problem. I did not realize that there was a difference between inheriting from a normal class and a template class. I needed to include

using Parent<type>::data_parent;