Create two class definitions.
This one is used in main() and other user files as a header file:
-
class MyClass
-
{
-
private:
-
MyClass();
-
public:
-
static MyClass* Instance();
-
void AMethod();
-
-
};
-
The constructor is private so you can't create on object in main().
However, the Instance() method is static and doesn't need an object. So you call it and that method returns the address a MyClass object, which is in another .cpp file.
In that other .cpp file you have:
-
class MyClass
-
{
-
public:
-
MyClass();
-
static MyClass* Instance();
-
void AMethod();
-
-
};
-
-
namespace
-
{
-
MyClass obj;
-
}
-
MyClass* MyClass::Instance()
-
{
-
return &obj;
-
}
-
In this file, the class defintion is different and is not in a header. That means it can only be used in this file where there is a global variable created in an anonymous namespace.
When you call the Instance() method from main() you call the function here and it returns the address of the global. You use that address in main() to call AMethod().
Inheritance is prohibited because the default constructor is private (and there are no other constructors in that header file) so any attempt to derive from this class will produce a compile error when you try to create the derived object.
This is an example of a Singletoin object. There is an article in the C/C++ Articles forum about Singleton objects.