Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Immediate object as a static member
#include <iostream>
using std::cout; using std::endl;
// A class whose instance will be included as a member of a monostate class
class CContent {
public:
CContent() {cout << "CContent constructor" << endl;}
~CContent() {cout << "CContent destructor" << endl;}
void speak() {cout << "Bonjour le monde !" << endl;}
};
// Monostate class, in other words, a class with only static members
class CMonostate {
public:
static CContent myInstance;
};
// You must define the substance of static members other than integers out of the class definition.
CContent CMonostate::myInstance = CContent();
// Do not forget the main function so that we can test this
int main() {
cout << "Program begins" << endl;
CMonostate::myInstance.speak();
cout << "Program ends" << endl;
}
/*
You will see...
CContent constructor
Program begins
Bonjour le monde !
Program ends
CContent destructor
(Tested with GCC 4.5.3 on Cygwin)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment