Copy Constructor

Why is that when declaring a copy constructor, the object being passed as argument to that constructor is (1) passed by reference using "&", and (2) the instantiated object is typecast as "const"?

1
2
3
4
5
6
class MyClass {
   public:
      MyClass( int len); // simple constructor
      MyClass( const MyClass &obj); // copy constructor
      ~MyClass(); // Destructor
};
You don't have to make a copy, when you use reference. Consider:
1
2
3
MyClass( MyClass obj ) {
 // make *this copy of obj
}

The obj is copy constructed, because it is a by value parameter.
If you can create obj, then you already know how to copy construct MyClass objects?

Reference avoids that recursion.


For const, consider:
1
2
3
4
5
6
class MyClass {
  MyClass( MyClass& obj );
};

const MyClass alpha;
MyClass bravo( alpha ); // error 

You can't have non-const reference to const object. Therefore, without the const you can't copy constant objects.
Thanks keskiverto. Thanks for your patience as I am an newbie. Two follow up questions if you don't mind please:

(1) In "const MyClass &obj", is obj being passed by value or by reference (i.e. its address)?
(2) Aren't we typecasting obj to be of type MyClass, and if so, why use const on top?
1) by reference is not by address (although internally it may be done using pointers). Yes, obj is passed by reference (not by address). To pass by address it would be MyClass* obj

2) const means that the contents of obj can't be changed in the function. Hence the passed-in value can be const or could be an r-value.
(2) Aren't we typecasting obj to be of type MyClass, and if so, why use const on top?

No, not "typecasting". Creating a reference. Look at:
1
2
3
4
void func( MyClass one, MyClass& two, const MyClass& three, const MyClass* ptr );

const MyClass obj;
func( obj, obj, obj, &obj );

During that function call the parameters are created like this:
1
2
3
4
MyClass  one = obj; // by value parameter, copy construction
MyClass& two = obj; // by reference. ERROR: obj is const
const MyClass& three = obj;  // by reference. ok
const MyClass* ptr   = &obj;  // by value. ok 
Topic archived. No new replies allowed.