What is the correct way to declare a copy constructor of a class named MyClass?
2013
What is the correct way to declare a copy constructor of a class named MyClass?
- A.
MyClass(const MyClass *arg)
- B.
MyClass(const MyClass &arg)
- C.
MyClass(MyClass arg)
- D.
MyClass(MyClass *arg)
Attempted by 205 students.
Show answer & explanation
Correct answer: B
In C++, a copy constructor has the same name as the class and takes an object of the same class by reference. For a class named MyClass, the standard declaration is:
MyClass(const MyClass &arg)
The reference avoids infinite recursion, and const prevents the source object from being modified. Therefore, option B is correct.