-2

I'm learning c++ here.

I'm learning more about inheriting and classes but I'm having the following issue:

class A
{
public:
   std::vector<int> vect1;
};

class B : A
{
public:
   int x, y;
};

class C : B
{
   c()
   {
      x=10;
      y=30;
      vect1.pushback(44);
   }
};

why cant i access vect1 from the class C? how can i achieve this?

i also tried:

class C : B, A {...}

but then it said vect1 is ambiguous (or something like that). im using visual studios.

thank you.

2 Answers2

5

why cant i access vect1 from the class C?

Because vect1 has private access. Sub classes can not access private members of a base class. They can only access protected or public members.

Furthermore, A is a private base of B, so sub classes of B have no access to it. Only protected or public bases are accessible to grand children.

The default access specifier of classes defined with the class keyword is private (The default is public for classes defined with the keyword struct). To declare a base with another access specifier, you can put the access specifier keyword right before each base in the declaration:

class B : protected A
{
    // ...
};

To declare members with another access specifier:

class A
{
protected:
   std::vector<int> vect1;
};
eerorika
  • 232,697
  • 12
  • 197
  • 326
3

To get access from derived to base class you should do both:

  • public inheritance
  • protected declaration

like the following:

#include <vector>

class A
{
protected:
   std::vector<int> vect1;
};

class B : public A
{
protected:
   int x, y;
};

class C : public B
{
public:
    C(){
       x=10;
       y=30;
       vect1.push_back(44);
    }
};
SHR
  • 7,940
  • 9
  • 38
  • 57
  • 1
    Exactly right. Extra detail for @CPPApprentice: default inheritance is private. So B derives privately from A, meaning it doesn't expose publicly anything that A exposed. – jwismar Nov 26 '18 at 14:44
  • _Default inheritance **for classes introduced with the `class` keyword** is private_. It is public for `struct`. – YSC Nov 26 '18 at 14:52
  • @YSC Added the word `class` – SHR Nov 26 '18 at 14:54
  • @SHR I was refering to jwismar comment ^^ "base class" apply for classes introduced with `class` or `struct` ;) Not a bad edit though. – YSC Nov 26 '18 at 14:55