Click here to Skip to main content
15,896,269 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++.
// StaticConstructorSample.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>

// Sample Files:
#include "MyClass.h"
#include "MyTemplate.h"


// Sample code for StartUp
STATIC_STARTUP_CODE()
{
	std::cout << "Starting up..." << std::endl;
}

// Sample code for FinishUp
STATIC_FINISHUP_CODE()
{
	std::cout << "Finishing up..." << std::endl;
}


// Template for testing each Type:
template <typename Type>
void TestType(const std::string& strType)
{
	using namespace std;

	// Static Constructor should have been already invoked:
	cout << "Show static data members before creating any instance of " << strType << ":" << endl;
	cout << "String: " << Type::StaticStr() << endl;
	cout << "PI: " << Type::PI() << endl;

	// Temporary block:
	// Destructor of local variable will be called at the end of this block.
	{
		Type myObj;
		cout << "Show static data members after creating an instance of " << strType << ":" << endl;
		cout << "String: " << myObj.StaticStr() << endl;
		cout << "PI: " << myObj.PI() << endl;
	}

	cout << "Show static data members after destroying the instance of " << strType << ":" << endl;
	cout << "String: " << Type::StaticStr() << endl;
	cout << "PI: " << Type::PI() << endl;
	cout << endl;
}


// Declaration of alias (class names) for the template instaces:
typedef MyTemplate<int>    MyTemplateInt;
typedef MyTemplate<double> MyTemplateDouble;

// Invoke the StaticConstructor & StaticDestructor for each one of the template instances:
// Should be called with alias (class names) for the template instaces.
INVOKE_STATIC_CONSTRUCTOR(MyTemplateInt);
INVOKE_STATIC_CONSTRUCTOR(MyTemplateDouble);


// Main:
int _tmain(int argc, _TCHAR* argv[])
{
	// Static Constructors have already been called before entering this function...

	// Run the same tests for each one of the classes:
	TestType<MyClass>("MyClass");
	TestType<MyTemplateInt>("MyTemplateInt");
	TestType<MyTemplateDouble>("MyTemplateDouble");

	// Static Destructors will be called after exiting this function...
	return 0;
}


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