Thanks, that fixes the second error. I hadn't realized it was a function. (I've never thought much of the OO concept of hiding data types and name my variables to indicate its type. e.g., "g_" for globals, "p" for pointers, etc.)
#include <iostream>
#include <stdexcept>
struct App // may be in app.h
{
int run() { return do_run() ; }
static App& this_app()
{
if( ptr_instance == nullptr )
throw std::logic_error( "no App object has been created!" ) ;
return *ptr_instance ;
}
protected:
App()
{
// do not allow a second instance
if( ptr_instance != nullptr )
throw std::logic_error( "a second instance of App is not alowed!" ) ;
else ptr_instance = this ;
}
virtualint do_run() = 0 ;
private:
static App* ptr_instance ;
App( const App& ) = delete ; // non-copyable
App( App&& ) = delete ; // and non-moveable
};
App* App::ptr_instance = nullptr ; // may be in app.cpp
int main()
{
// illustrative:may be implemented as a component (my_app.h/my_app.cpp)
struct my_app : App
{
protected: virtualint do_run() override
{ std::cout << "running my_app\n" ; return 0 ; }
};
static my_app this_app ; // this object is available till end of program
// illustrative: App::this_app() may be called from anywhere in the program
return App::this_app().run() ;
}
Ah, thanks for your thought-out post. I would learn some new C++ idioms if I studied your code, but before I invest the non-trivial (for me) time, I want to make sure it is directed toward my need. Class App is not provided by any library. It is not polymorphic. I simply want to have a way to have application-wide access to application-wide properties/variables (hence the globally-scoped pointer g_pApp to the only instance of App there will be at runtime). It's an old-style way to handle it that I used to use. If there is a more modern/acceptable way, please do tell. I was proficient/advanced in C++, but a 15 year break does violence to one's memory.
#include <iostream>
struct App
{
int run() { std::cout << "running app\n" ; /* ... */ return 0 ; }
static App& this_app() { return *ptr_instance ; } // ideally: add check for nullptr
App() { ptr_instance = this ; /* ... */ } // ideally: prevent second instance
private: static App* ptr_instance ;
// ideally: make non-copyable, non-moveable
};
App* App::ptr_instance = nullptr ;
int main()
{
static App my_app ; // this object is available till end of program
// illustrative: App::this_app() may be called from anywhere in the program
return App::this_app().run() ;
}