Search code examples
c++constantsdirect3dconst-correctnessdirect3d11

Why am I allowed to call this->deviceContext->map() from a const member function?


I don't understand why this is allowed:

void Renderer::UpdateTextureFromArray(unsigned int* colors, unsigned int size, TextureData* textureData) const
{
    D3D11_MAPPED_SUBRESOURCE ms;
    this->deviceContext->Map(textureData->texture, 0, D3D11_MAP_WRITE_DISCARD, NULL, &ms);

    memcpy(ms.pData, colors, sizeof(unsigned int) * size * size);
    this->deviceContext->Unmap(textureData->texture, 0);
}

I made the UpdateTextureFromArray function const, yet I'm still allowed to call a non-const function on its members?

In this case, is it bad style for me to label the function as const?

EDIT: To clarify, is it "lying" to society if I have a function like this const? In a perfect world, this code wouldn't compile, right?


Solution

  • Presumably deviceContext is a pointer data member, so a const method cannot modify the pointer. But is is allowed to modify the object the pointer points to:

    struct Bar {
      void bar() {} // non const method
    };
    
    struct Foo {
      Foo() : p(0) {}
      void foo() const { p->bar();} // const method calling non-const method of Bar
      Bar* p;
    };
    
    int main()
    {
      const Foo f;
      f.foo();  // OK, Foo::p is not modified
    }