0

Hello I have trouble with working an inheritance constructor. I can't access the parent's fields.

Here is my MyClass.h:

#include "Parent.h"
class MyClass : public Parent {
  public:
    MyClass(string otherParameters);

};

Here is MyClass.cpp:

#include MyClass.h
MyClass::MyClass(string otherParameters) : Parent() {
    parent_field = "something";
}

The field otherParameters does not come from Parent and pertains only to the class MyCLass. The compiler pops out errors and tells me Parent::parent_field is private. I don't undersrtand, my class MyClass should have inherited this parent_field attribute, so why can't I have access to it? Thanks

Alexandre Toqué
  • 173
  • 1
  • 3
  • 11

3 Answers3

1

MyClass only has access to Parent's public and protected members. If parent_field is a private member of Parent, then MyClass cannot see it (unless you declare MyClass to be a friend of Parent, which would be an odd design).

It looks like you want to be able to set parent_field via a Parent constructor:

struct Parent
{
  Parent(const std::string& s) : parent_field(s) {}
  // other code as before
};

then use it in MyClass's constructor:

MyClass::MyClass(string otherParameters) : Parent("something") {}

This would set Parent::parent_field to "something".

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

Here's a good question discussing access modifiers, private, protected and public. private is only visible by your class, not to anyone inheriting from it. What you need to do is either declare parent_field protected in Parent, or have some other way of accessing it, like having a setter or constructor argument.

Also, the fact that you inherit it as public means, that anyone inheriting from MyClass will not have a restricted view of Parent, however, Parent still decides what it wants to expose, how you inherit it doesn't change that. The only thing you can do is restrict how classes inheriting MyClass is able to access stuff from Parent, but you cannot remove any restrictions imposed already.

Community
  • 1
  • 1
falstro
  • 34,597
  • 9
  • 72
  • 86
1

Because it's private. Functions and variables in the private section of a class is only available to that class and that class alone. If you want to be able to use functions or variables in inherited classes, but still not allow them to be public, you have to put them in the protected section.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621