First, my latest coding is Java, and I do not want to “write Java in C++”.
Here’s the deal, I have to create an immutable class. It’s fairly simple. The only issue is that getting the initial values is some work. So I cannot simply call initializes to initialize my members.
So what’s the best way of creating such a class? And how can I expose my immutable / final properties to the outside world in C++ standards?
here’s a sample class:
class Msg {
private:
int _rec_num;
int _seq;
string text;
public:
Msg(const char* buffer) {
// parse the buffer and get our member here...
// ... lots of code
}
// does this look like proper C++?
int get_rec_num() { return _rec_num; }
};
C++ offers some nice mechanisms to make your class immutable. What you must do is:
constoperator=as privateThis will ensure that your objects cannot be modified after they have been created. Now, you can provide access to your now immutable data members anyway you want, using const methods. Your example looks right, provided that you make it
const:EDIT: Since
C++11you can explicitly deleteoperator=, rather than just leave it undefined. This explicitly instructs the compiler to not define a default copy assignment operator: