Access to a public member of a base class from a derived class

Is it possible to access the public member of the base class from an instance of the derived class in some other places 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 the above code, I got the following error.

 `error: 'int base::x' is inaccessible` 
+4
source share
6 answers

You inherit privately from the base class. Usually you need public inheritance:

 class derived : public base 

Here is the FAQ for private inheritance.

+5
source

The problem is that you accidentally use private inheritance here

 class derived : base { 

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

Change it to

 class derived : public base { 

and it will work as expected.

+7
source

You must inherit from base public, then.

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

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

+3
source

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

To make it available, you need inheritance:

 class derived : public base ^^^^^^ 
+1
source

Try:

 class derived : public base { ... }; 
+1
source

Use public inheritance:

 class derived : public base { ... }; 

or

Make x private, not public, and use the 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; } 
0
source

Source: https://habr.com/ru/post/1443237/


All Articles