-1

My question really says it all but i'll just reiterate the problem.

In class A there is a protected variable I am trying to access (a vector).

Class B is a subclass of class A and, in its constructor, can access and add to this vector as it likes.

However, in class C (which is a subclass of class A) I would like to add to this vector in its constructor, but the compiler tells me off.

Here is my code:

Class A:

class ClassA
{
protected:
    std::vector<Object *> myVector;
};

Class B:

class ClassB : ClassA, AnotherClass
{
public:
    ClassB()
    {
        this->myVector.push_back(new Object);
    }
}

Class C:

class ClassC : public ClassB
{
public :
    ClassC()
    {
        this->myVector.pushBack(new Object);
    }
}

Can anyone tell me if what I'm doing is impossible due to constraints of C++ or because of my code?

Thanks as always.

Adam Carter
  • 4,741
  • 5
  • 42
  • 103

4 Answers4

1

ClassB inherits ClassA privately. This means that all inherited members are private to ClassB, and therefore not accessible in ClassC.

The solution depends on your requirements, which are not stated in your question. It could be as simple as using public inheritance:

class ClassB : public ClassA, AnotherClass

Another alternative would be to give ClassB a public or protected member function that allows to modify the vector from ClassC.

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

Change ClassB to:

class ClassB : public ClassA, AnotherClass
{
public:
    ClassB()
    {
        this->myVector.push_back(new Object);
    }
}
zumalifeguard
  • 8,648
  • 5
  • 43
  • 56
0

The issue is that ClassB only "imported" the private members of ClassA.

To get your code to work you want to do either prepend either "protected" or "public" infront of ClassA for your definition of ClassB like so:

class ClassB : protected ClassA, AnotherClass
Vitali
  • 321
  • 1
  • 2
  • 10
0

The issue is you did not declare what type of inheritance classA is for subclass classB. The following code compiles for me just fine. (change the inheritance to public classA)

class classA{
  protected:
    int a;
};

class classB : public classA{
  public:
  classB()
  {

    this->a = 0;
  }

};

class classC : public classB
{
  public:
  classC()
  {
    this->a = 1;

  }
};
unfuse
  • 35
  • 5