C++ class demonstration

A C++ 11 class has various constructors and assignment operators. There are default constructor, copy constructor and move constructor.

Lets consider our class to contain following members:

class Expample {
	int *ref;
	int id;
public:
		// Constructors:
	Example();                   // Default constructor
	Example(int id);             // User constructor
	Example(const Example&);     // Copy constructor
	Example(Example&&);          // Move constructor (only in C++ 11)
	
		// Destructor:
	~Example();
	
		// Assignment operators:
	Example& operator= (const Example&);   // Copy assignment
	Example& operator= (Example&&);        // Move assignment
}

Thus our class contains two fields: a pointer to an integer and an integer id.

Let's write its default constructor. It is a constructor of an "empty" object. We should initialize the reference by a null value.

Example() {
	ref = nullptr;
	id  = 0;
}

This constructor will be called in following statements (variable definitions):

Example ex;
Example ex();
Example ex = Example();
Example *ex = new Example;
Example *ex = new Example();

Test program

This program demonstrates usage of different class constructors and assignments, including move constructor and assignment.

Source code: main.cpp

Example of output: log.txt

Сайт создан исключительно в образовательных целях. По всем вопросам с администрацией сайта можно связаться по электронной почте admin@dcsr.ru. Вход для редактора.