Using copy constructors
Copy constructors are used to copy one object to another. C++ provides us with a default copy constructor, but it is not recommended. We should write our own copy constructor for better coding and organizing practices. It also minimizes crashes and bugs that may arise if we use the default copy constructor provided by C++.
Getting ready
You need to have a working copy of Visual Studio installed on your Windows machine.
How to do it…
In this recipe, we will see how easy it is to write a copy constructor:
- Open Visual Studio.
- Create a new C++ project.
- Select Win32 Console Application.
- Add source files called
Source.cpp
andTerrain.h
. - Add the following lines of code to
Terrain.h
:#pragma once #include <iostream> using namespace std; class CTerrain { public: CTerrainCTerrain(); ~CTerrain(); CTerrain(const CTerrain &T) { cout << "\n Copy Constructor"; } CTerrain& operator =(const CTerrain &T) { cout << "...