Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does inheritance break encapsulation in C++

I read (Scott Myers) that inheritance breaks encapsulation. When data/internal methods are private (not protected), is encapsulation broken?

e.g.

class Vehicle
{
  int color;

public:
  void set_color();
  int get_color();
}


class Car: public Vehicle
{
public:
  void change_tires();
}

I can change the internals of Vehicle without breaking Car ever knowing, correct?

like image 344
MustafaM Avatar asked Jun 25 '26 06:06

MustafaM


1 Answers

Phrases like "inheritance breaks encapsulation" are often taken out of context.

What the phrase refers to is the fact that the virtual interface being inherited is now not encapsulated. In effect, inheritance means that certain things that were hidden are now exposed. Things like protected members and virtual private members are all open for play by derived classes.

Non-virtual private members are still hidden.

like image 87
Nicol Bolas Avatar answered Jun 26 '26 19:06

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!