Why close class members?

I have been studying C ++ for some time, however there is always this question that puzzles me (for many years). At school, our teachers love to declare class variables private. To access it, we must declare an accessor to access it.

Sometimes we even have to force different classes to become β€œfriends” to access its elements.

My question is: Why is it so troublesome? What is the true rationale for all private and secure things when we can just make our life a programmer easier by using the public for everything?

I thought, as soon as the code is compiled, the end user will not even differentiate whether we will use public or private in coding with the opposite end, so why else declare it properly as closed, protected ... etc.

+4
source share
3 answers

Make code easier to understand and maintain.

When you create a data member public, other programmers who use your class will naturally use these public elements, rather than some member function that provides the same or the same information simply because it is simpler. You might even do it yourself. This is understandable - programmers are by nature lazy beasts .

, , - , , -, -. , , - . , - , .

. , , , :

class Gizmo
{
public:
  std::string mSku;
};

, , , . , mSku - , - "12345".

, , . , Amazon, . , mSku, . skus: S:12345, Z:12345.

, , , mSku , , . . 1 - . , , , mSku. , , . .

, mSku, -, , . - :

class Sku
{
public:
  std::string ProductNumber() const;
private: 
  std::string mSku;
};

mSku , . , ProductNumber() , 1 - .

, . class private, - . protected, public.

[ ] , ?

, , , private .

+6

private:, , , . , - , , , . - , .

, , . , , , . .

+5

. ++ 11.1.

, - ++.

, . , , ( ).

, , . . , , , - . , - .

0

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


All Articles