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;
}
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'
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)
#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;
}