Constructor and destructor

Constructor

Class has special member function called constructor. Constructor initializes an object of a class. Constructor has the same name as the class name. Example:

#include <iostream>
class MyClass{
public:
	MyClass(){ // constructor
		std::cout << "Object created." << std::endl;
};

int main(){
	MyClass o; // Object created, constructor invoked
}

Constructor without parameters is called a default constructor. If you don't declare one the compiler will declare one for you. Constructors can have parameters and be used to initialize the data members:

#include <iostream>
class MyClass{
public:
	int x;
	MyClass(int value){
		std::cout << "Object created." << std::endl;
		x = value;
		std::cout << "Value set to: " << x << std::endl;
};

int main(){
	MyClass o(123);
}

Or through an initializer list:

#include <iostream>
class MyClass{
public:
	int x;
	int y;
	MyClass(int valuex, int valuey) : x(valuex), y(valuey){
		std::cout << "Object created." << std::endl;
		std::cout << "X is: " << x << " Y is: " << y << std::endl;
};

int main(){
	MyClass o(123, 456);
}

Destructor

Destructor is a special member functions that gets invoked when an object is destroyed - its lifetime ends / object goes out of scope. Destructors have the same name as the class prepended with the ~ sign. Example:

#include <iostream>
class MyClass{
public:
	MyClass(){ // constructor
		std::cout << "Object created." << std::endl;
	~MyClass(){ // destructor
		std::cout << "Object destroyed." << std::endl;
};

int main(){
	MyClass o; // Object created, constructor invoked
			     // Object destroyed, destructor invoked
}