Search code examples
c++initializationheader-files

Calling functions from header files as an initializer for const variables


In my C++ code, I recently updated a variable called bufferSignature from an unsigned int to a const string to be more descriptive. I need to initialize this variable on the creation of the VBufferObject with the return value from a function called GenerateAlphanumSignature() in the SceneManager namespace.

The problem I'm having here is that I want the variable (bufferSignature) to be const, as I won't be updating it at all in its lifetime. But I can't initialize it in a constructor. I've tried calling the function in the header to initialize the variable.

I've never had to do this before, so I didn't expect it to work. It didn't. I'm just looking for any workaround on this.

VBufferObject.h

#pragma once
#include "Dependencies.h"
#include "Helpers.h"

#include "SceneManager.h"

namespace Vega
{
    class VBufferObject
    {
    public:
        const std::string bufferSignature = SceneManager::GenerateAlphanumSignature();

        void ComputeIndexArray();

        std::vector<unsigned int> IBD;
        std::vector<glm::vec3> VBD;
        std::vector<glm::vec2> UVBD;
        std::vector<glm::vec3> NBD;
    };
}

The code is completely open source: here (branch: preview) if you need to look through the code yourself.


Solution

  • I can't initialize it in a constructor

    Yes, you can, actually. Use the constructor's member initialization list, eg:

    class VBufferObject
    {
    public:
        const std::string bufferSignature;
    
        VBufferObject();
        ...
    };
    
    VBufferObject::VBufferObject()
        : bufferSignature(SceneManager::GenerateAlphanumSignature())
    {
    }