4

Is it possible to access base class public member from instance of derived class in some other locations in the program.

class base {
public:
    int x;

    base(int xx){
    x = xx;
    }
};

class derived : base {
public:
    derived(int xx) : base(xx){
    }
};

class main {
public:
    derived * myDerived;      

    void m1(){
        myDerived = new derived(5);
        m2(myDerived);  
    }

    void m2(derived * myDerived){
        printf("%i", myDerived->x);
    }    
};

After above code, I got following error.

`error: 'int base::x' is inaccessible`
Kara
  • 6,115
  • 16
  • 50
  • 57
utvecklare
  • 671
  • 1
  • 11
  • 25

6 Answers6

8

The problem is that you accidentally use private inheritance here

class derived : base {

This makes all base class members private in the derived class.

Change this to

class derived : public base {

and it will work as expected.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
6

You inherit privately from the base class. What you typically need is public inheritance:

class derived : public base

Here is the FAQ on private inheritance.

nogard
  • 9,432
  • 6
  • 33
  • 53
3

You should inherit from base publicly, then.

class derived : public base {
public:
    derived(int xx) : base(xx){
    }
};

Private inheritance is used in very specific circumstances, such as when you have a has-a relationship between two classes, but you also need to override a member of the base class.

Alex
  • 7,728
  • 3
  • 35
  • 62
1

From outside the class, you can only access public members of public base classes; and inheritance is private by default when you define a class using the class keyword.

To make it accessible, you need public inheritance:

class derived : public base
                ^^^^^^
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

Try:

class derived : public base {
    ...
};
cjamesm
  • 109
  • 7
0

Use public inheritance:

class derived : public base {
  ...
};

or

Make x private instead of public and use following code:

class Base {
        int x;
        public:
            Base (int xx) {
                x = xx;
            }
            void display() {
                cout << "x = " << x << endl;
            }
    };

    class Derived : public Base {
        public:
            Derived (int xx) : Base (xx) {
            }
    };

    int main() {
        Derived d1(2);
        Derived *d = new Derived(10);
        d->display();
        d1.display();
        return 0;
    }
Alexey
  • 5,898
  • 9
  • 44
  • 81