Why use gets and sets in classes?

Asked

Viewed 569 times

1

What is the reason and when to actually use gets and sets instead of a publish variable in classes?

They say it is a bad practice to use and modify a variable as public, why?

Example 1:

class Teste
{
private;
    std::string nome;
public:
    std::string getNome() const { return this->nome };

    void setNome(std::string _nome) { this->nome = _nome; }
};

 Teste Teste;
 teste.setNome("Fulano");
 std::cout << "Nome: " << teste.getNome() << std::endl;

Example 2:

class Teste
{
public:
   std::string nome;
};

Teste teste;
teste.nome = "Sicrano";
std::cout << teste.nome << std::endl;
  • 1

    Also https://answall.com/q/25995/101, https://answall.com/q/110785/101 and https://answall.com/q/134750/101

  • Thank you Maniero, most is about other languages more all right, I believe it applies to C++ too and sorry for the duplicate question.

  • Yes, if it applies, it follows the links. inside them, has more material yet. Form your conclusion.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.