Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing base class public member from derived class

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`
like image 689
utvecklare Avatar asked Nov 30 '22 22:11

utvecklare


1 Answers

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.

like image 88
Bo Persson Avatar answered Dec 04 '22 14:12

Bo Persson