KcFnMi KcFnMi - 16 days ago 6
C++ Question

One object accessible across all my application classes

I would like to have an object accessible across all my application classes. So I though:

#include <iostream>

using namespace std;

class MyClass {
public:
MyClass(){}
int id(){return -1;}
};

extern const MyClass myClass;

int main() {
cout << myClass.id();
return 0;
}


And anywhere I need it, I'll do:

extern const MyClass myClass;

and just use it, like:

cout << myClass.id();


But, I was wrong. That returns error:

error: passing 'const MyClass' as 'this' argument of 'int MyClass::id()' discards qualifiers [-fpermissive]


I Guess I could do
static MyClass myClass;
, instead. And so I will have more or less the same functionality.

What's the best/correct approach?

Answer

Either discard the const in the declaration and definition:

extern /* const */ MyClass myClass;
    // ^^^^^^^^^^^

or make the id() function const:

int id() const {return -1;}
      // ^^^^^

I Guess I could do static MyClass myClass;, instead. And so I will have more or less the same functionality.

A static variable would make only sense as a class member.

What's the best/correct approach?

If you want to ensure that there exists only one instance of the class better use the Singleton Pattern:

class MyClass {
    MyClass(){}
public:
    static Myclass& instance() {
        static MyClass theInstance;
        return theInstance;
    }
    int id(){return -1;}
};

So you can access the single class instance from everywhere using e.g. MyClass::instance().id(), and forbid construction of other instances.