Search code examples
c++classcopy-constructorassignment-operator

Pass reference instance to static method when copy-constructor and assignment-operator is disabled


My ClassA looks like this:

class ClassA
{
private:
    static uint32_t IDCOUNTER;
    uint32_t _id = -1;

public:
    ClassA();
    ~ClassA();
    ClassA(const ClassA&) = delete;
    void operator=(const ClassA&) = delete;
};

I want to create one specific instance of ClassA and I want it to be passed around but I don't want it to ever be duplicated in any way. So, in my main function I instantiate instanceA1. Next, (in my main function), I want to store this instance somewhere global, like in a static class:

int main()
{
    ClassA instanceA1;
    ClassStatic::SetClassA(&instanceA1);
}


// this class is declared in a separate file:
class ClassStatic
{
private:
    static ClassA *referenceToA;

public:
    static void SetClassA(ClassA* refToSingleAInstance)
    {
        referenceToA = refToSingleAInstance; // taken from cpp part of the class just for this question
    }
};

When compiling, I get a linker error. Why is that? Am I getting the whole concept wrong (seems likely...)? How would I fix this?


Solution

  • When compiling, I get a linker error. Why is that?

    Because you didn't define ClassStatic::referenceToA.

    How would I fix this?

    Define ClassStatic::referenceToA in (exactly one) translation unit.