Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiler provides default copy constructor

I wanted to know Why compiler provides default copy constructor..Whats the strategy behind that idea.

Thanks in Advance.

like image 929
Mahesh Avatar asked Sep 30 '09 15:09

Mahesh


People also ask

Does compiler provide default copy constructor?

In C++, compiler created default constructor has an empty body, i.e., it doesn't assign default values to data members. However, in Java default constructors assign default values. The compiler also creates a copy constructor if we don't write our own copy constructor.

Why a compiler given constructor is called as default constructor?

A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example: public class Student { String firstName; String lastName; int age; public static void main(String args[]) { Student myStudent = new Student(); myStudent.

Why compiler gives a default constructor in Java?

The Java compiler provides a default constructor if you don't have any constructor in a class. The method is not provided by the compiler in any case. The constructor name must be same as the class name.

What is the use of default copy constructor?

1. The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. 2. Copy constructor takes a reference to an object of the same class as an argument.


1 Answers

From a related (but not same) question - Why don't C++ compilers define operator== and operator!=?:

Stroustrup said this about the default copy constructor in "The Design and Evolution of C++" (Section 11.4.1 - Control of Copying):

I personally consider it unfortunate that copy operations are defined by default and I prohibit copying of objects of many of my classes. However, C++ inherited its default assignment and copy constructors from C, and they are frequently used.

So the answer is that it was included reluctantly by Stroustrup for backwards compatibility with C (probably the cause of most of C++'s warts, but also probably the primary reason for C++'s popularity).

For my own purposes, in my IDE the snippet I use for new classes contains declarations for a private assignment operator and copy constructor so that when I gen up a new class I get no default assignment and copy operations - I have to explicitly remove the declaration of those operations from the private: section if I want the compiler to be able to generate them for me.

like image 77
Michael Burr Avatar answered Sep 21 '22 20:09

Michael Burr