Click here to Skip to main content
15,896,154 members
Articles / Programming Languages / C++

Static Constructor in C++

Rate me:
Please Sign up or sign in to vote.
3.71/5 (7 votes)
27 Nov 2011CPOL5 min read 79.8K   752   29  
An easy way to implement static constructors and static destructors in standard C++.
// MyClass.cpp
//
#include "stdafx.h"
#include "MyClass.h"


// Initialization of protected static data members:
void*        MyClass::mpStaticMemory = NULL;
const double MyClass::mPI            = 3.141592;
std::string  MyClass::mStaticStr     = "Init Value";


// Invoke the StaticConstructor & StaticDestructor of the class:
// Make sure you put this AFTER the initialization of the static data members!
INVOKE_STATIC_CONSTRUCTOR(MyClass);


// Default Constructor:
MyClass::MyClass()
{
//	PI = 5.0; // Cannot be done, as PI is const
	mStaticStr = "Modified by Default Constructor";
}

// Destructor:
MyClass::~MyClass()
{
	mStaticStr = "Modified by Default Destructor";
}

// Static Constructor:
void MyClass::StaticConstructor()
{
	mStaticStr = "Modified by Static Constructor";
	mpStaticMemory = new double[10];
}

// Static Destructor:
void MyClass::StaticDestructor()
{
	delete[] mpStaticMemory;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Spain Spain
B.Sc. Mathematics and Computer Science.
Programming in C++ since 2003.

Comments and Discussions