private.h
#ifndef PRIVATE_H
#define PRIVATE_H
#include <string>
class OlaMundo {
public:
OlaMundo(std::string);
void mostrarMsg();
private:
std::string mensagem;
};
#endif
private.cpp
#include "private.h"
#include <iostream>
OlaMundo::OlaMundo(std::string msgArg) {
mensagem = msgArg;
}
void OlaMundo::mostrarMsg() {
std::cout << "Olá, " << mensagem << "!" << std::endl;
}
Test: main.cpp
#include "private.h"
int main()
{
OlaMundo ola("Rafael");
ola.mostrarMsg();
}
Why can not declare private member data ( std::string mensagem
) in implementation (private.cpp)? Would not it be better software engineering to leave only the public interface available and encapsulate the internal behavior of functions - how do you intend it?
Note: The private.cpp code could be done the way (by removing the private key from the corresponding header:
#include "private.h"
#include <iostream>
std::string mensagem;
OlaMundo::OlaMundo(std::string msgArg) {
mensagem = msgArg;
}
void OlaMundo::mostrarMsg() {
std::cout << "Olá, " << mensagem << "!" << std::endl;
}
Could this be considered as good engineering in C ++? The data has become "private" by header and not by class definition. Why is it necessary for privates data in the headers?