Default Copy Constructor
Objectives:
To familiarize students with class default copy constructorTools:
Turbo C++ IDE
Procedure:
Writing C++ language program to perform the following tasks
Copy constructor:
A copy constructor is a special constructor in the C++ programming language for creating a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed, which might be followed by parameters of any type. Normally the compiler automatically creates a copy constructor for each class known as an implicit copy constructor but for special cases we creates the copy constructor, known as a userdefined copy constructor. In such cases, the compiler does not create one. Hence, there is always one copy constructor that is either defined by the user or by the system. A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written. One object passed to another object as an argument which means that object being passed as argument is copied to the object which is created.
Step 1: Create New C++ Program File and save it as lab9.cpp
Figure 26 (b): Default Copy Constructor
Figure 27: Default Copy Constructor
Try these Task(s): Write C++ language program to perform following tasks
• Create a class Distance of private integer variables feet and float variable inches. The public part must consist of default constructor, an overloaded constructor with two arguments, and a function showdist() to display feet and inches. Declare three objects of class as obj1, obj2 and obj3. Copy obj1 to obj2 and obj3 and finally display values by calling showdist() function through objects.
• Create a class person with private data variable age and one argument constructor as public. Create two objects khan and ahmad, copy object khan to ahmad, and display data variable age value in main via both objects.
No comments:
Post a Comment