neo-mashiro
neo-mashiro

Reputation: 534

In C++, how to declare a class member that can only be changed externally?

I have a class like this

class Foo {
  public:
    Matrix M;

    Foo();
    ~Foo();
}

I want M to be immutable inside the class (internal member functions cannot change it), but code outside the class should be able to update it without constraint, is there a way to do so?

A little background: I'm working on an OpenGL application, where I have a Mesh class that holds all the vertices/textures data and can Draw() on demand. I realized that the viewing matrix and projection matrix are global to the scene, while the model matrix M is local to every mesh, so I declared M as a public member of the Mesh class, which is initialized to the identity matrix. The caller outside the class should update M every frame to do transformations. However, I don't want it to be accidentally changed from within the class. Hope this makes sense.

This seems to be violating the c++ principles, but I need to somehow tie M to an instance of the class. The Matrix type is actually glm::mat4 btw.

Upvotes: 3

Views: 332

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596332

Move M outside of Foo, and then give Foo a const pointer/reference to M, eg:

Matrix M;

class Foo {
  public:
    const Matrix &Mref;

    Foo() : Mref(M) {}
    ~Foo();
};

Upvotes: 6

Zoso
Zoso

Reputation: 3465

How about something like

struct Matrix {
    void change() {}
};

class Foo {
  public:
    Matrix M;
    void bar() const {
        // M.change(); can't change since it's a const function.
    }
    Foo();
    ~Foo();
};

int main() {
    Foo f;
    f.M.change();
}

Have all operations inside Foo within const functions, yet expose M itself to the outer world.

Upvotes: 3

Related Questions