4
Implementation concealment is one of the keys to good modern software engineering, and crucial in code reuse. Why then, in c++ is it not possible to hide the private data implementation? Since these members data can basically be used only by functions members of the class (or friends). Given the usual code below:
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;
}
Testing: main.cpp
#include "private.h"
int main()
{
OlaMundo ola("Rafael");
ola.mostrarMsg();
}
Why it is not possible to declare the members data private (std::string mensagem
) in implementation (private.cpp)? It would not be a better software engineering to leave only the public interface available and encapsulate the internal behavior of the functions - as is intended?
Observing: The private.cpp code could be done in the form (by removing the private mybro 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;
}
this could be considered as a good engineering in C++? The data became "private" by header and not by class definition. Why it is necessary to put privates data on headers?
It is not impossible for different libraries to define different methods with the same name for the same class: see Extension methods of C#, for example. In addition, other languages (such as C#, via partial classes, or Python, via Monkey patching) allow you to define methods over multiple files (although the namespacing problem is the programmer’s responsibility). C++ requires class definition to be centralized in a file (and exposed to users) because references to attributes are resolved at compile time (as is done in C), not at link-edit time.
– user25930