Constructor and Destructor

    When an object is created, it needs to be initialized, and the constructor is used. In other words, the role of the constructor is to initialize the object.

    Destructors are used to free the memory of an object.


Defining constructors and destructors in a class

example

class Point
{
public:
	Point(int x, int y)
	{
		X = x;
		and = and;
		cout << "Constructor is called";
		displayxy();
	}
	void displayxy()
	{
		cout << "(" << X << "," << Y << ")" << endl;
	}
	~Point()
	{
		cout << "Destructor is called";
		displayxy();
	}
private:
	int X, Y;
};

It can also be declared inside the class and defined outside the class

example

class Point
{
public:
	Point(int x, int y);
	void displayxy();
	~Point();
private:
	int X, Y;
};
Point::Point(int x, int y)
{
	X = x;
	and = and;
	cout << "Constructor is called";
	displayxy();
}
void Point::displayxy()
{
	cout << "(" << X << "," << Y << ")" << endl;
}
Point::~Point()
{
	cout << "Destructor is called";
	displayxy();
}

:: is a scope operator, indicating that the following member function is declared in this class

The destructor is automatically called at the end of the program, and the following is the output of the above code



Copy constructor (aka copy constructor)

Its function is to use an existing object to initialize another object. In order to ensure that the referenced object is not modified, the reference parameter is usually declared as a const parameter.

example

<class name>::<class name>(const <class name> & <object name> )
{
<function body>
}

It is automatically called when:

  • When an object of a class is used to initialize another object of that class.
  • When the formal parameter of the function is an object of the class, the formal parameter and the actual parameter are combined.
  • When the return value of the function is an object of the class, when the function execution completes and returns to the caller.

example:

  • Point p2=p1;//Create a new object p2 with object p1, call the copy constructor
  • p2=func(p1);//In func(), the copy constructor is called, and when the formal parameter p is initialized with p1, the object p is assigned a value
  • return pp;//pp is the object. When the return pp; is executed, a temporary object is created with the object pp and the copy constructor is called

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645748&siteId=291194637