C++:: Constructors and Destructors

Constructor

Constructors in C++ are special member functions of a class. A Constructor is a function that initilizes the members of object.There can be any number of overloaded constructors inside a class.The Constructor is automatically called whenever an object is created or dynamically allocated using "new" operator.

If no constructor is supplied then a default one is created by the compiler without any parameters.If you supply a constructor with parameters then default will NOT be created.

Some Points about Constructor:

-- Constructors have the same name as the class.
-- Constructors do not return any values.
-- Constructors are invoked first when a class is initialized. Any initializations for the class members,memory allocations are done at the constructor.
-- Constructors are never virtual.

Ex:

Class Sample{

public:
Sample(){ ..}
};


Destructor

Destructors in C++ also have the same name,except that they are preceded by a '~' operator. The destructors are called when the object of a class goes out of scope.The main use of destructors is to release dynamic allocated memory.Destructors are used to free memory,release resources and to perform other cleanup.If the destructor is not declared inside a class,the compiler automatically create a default one.

If the constructor/destructor is declared as private,then the class cannot be instantiated.

Ex:

~Sample()

.

C++ Basics
Class
Objects
Memory Management
Inline
Static
Overloading
Polymorphisam
Virtual Functions
Inheritance
Friend
Templates
Singleton
STL


C++:Singleton Class

Definition:

A class whose number of instances that can be instantiated is limited to one is called a singleton class. Thus, at any given time only one instance can exist, no more.

Can you give me an example, where it is used?

The singleton design pattern is used whenever the design requires only one instance of a class. Some examples:
  • Application classes. There should only be one application class. (Note: Please bear in mind, MFC class 'CWinApp' is not implemented as a singleton class)
  • Logger classes. For logging purposes of an application there is usually one logger instance required.