Why use gets and sets in classes? [duplicate]

1

What is the reason and when actually using gets and sets instead of a variable published in classes?

They say that 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;
    
asked by anonymous 30.10.2017 / 22:18

0 answers