-3

I started understanding the inheritance concept in c++. We have this statement:

The derived class inherits members and methods of the base class.

So, I run the following example to apply the above statement:

    class A {
    public:
        int a;

        A(int val){a=val;}

        void afficher(){  cout << a <<endl; }

    };

    class B : A {
    public:
        B(int val) : A(val){};
    };

    int main(){
        A a(5);
        a.afficher();

        B b(6);
        b.a = 4;
        b.afficher();
        return 0;
    }

I got the following errors when calling the member a and the method afficher() by the instance b that contradicts the statement:

error: 'int A::a' is inaccessible

error: 'void A::afficher()' is inaccessible

My question : how to call members and methods of the base class by a derived instance?

underscore_d
  • 6,309
  • 3
  • 38
  • 64
Zoya
  • 1,195
  • 2
  • 12
  • 14

1 Answers1

1

Just as for members, the default accessibility of bases for a type declared with the class keyword is private. Therefore, your B inherits everything from A as private members, hence those errors.

Change it to class B: public A.

underscore_d
  • 6,309
  • 3
  • 38
  • 64