public inheritance question

I thought public inheritance only inherited protected and public. Does it also inherit private, but we just can't access them as we normally would?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class A
{
public:
  int getMoney() { return money; }
  void setMoney(int n) { money = n; }
private:
  int money;
};

class B: public A
{
public:
private:
};

int main()
{
  A objectA;
  B objectB;
  objectB.setMoney(100); // My question is here...no private var in B class??
                         // the value is actually set
  return 0;
}
Last edited on
https://en.wikipedia.org/wiki/Liskov_substitution_principle
if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of T (correctness, task performed, etc.)
For `objectB' to be able to pass as an `A' it must have its members.

> we just can't access them as we normally would?
¿how would you normally access them?
in main() you must also use `getMoney()' and `setMoney()' on `objectA'
we just can't access them as we normally would?

More or less: we can’t access them - period. But they are there.
http://en.cppreference.com/w/cpp/language/derived_class:
cppreference wrote:
Public inheritance
When a class uses public member access specifier to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class (private members of the base are never accessible unless friended)

Your example, adjusted:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

class A {
public:
    int getMoney() const { return money; }
    void setMoney(int n) { money = n; }
private:
    int money;
};

class B: public A {
public:
    // error: 'int A::money' is private within this context:
//    void setMoneyInA_TheWrongWay(int value) { money = value; }

    void setMoneyInA_Allowed(int value) { setMoney(value); }
    int getMoneyFromA() const { return getMoney(); }
private:
};

int main()
{
    A objectA;
    B objectB;
    objectB.setMoneyInA_Allowed(100); // you don't need to know anything about A
    std::cout << objectB.getMoneyFromA() << '\n';
    return 0;
}

Topic archived. No new replies allowed.