-3

I want to know the difference between the Class(const Class & c) constructor and the Class(Class & c) constructor in C++.

class Class
{
public:
    Class()
    {
       cout << "running Class()..." << endl;
    }
    Class(Class& c)
    {
        cout << "running Class(Class& c)..." << endl;
    }
    Class(const Class& c)
    {
        cout << "runing Class(const Class& c)..." << endl;
    }
};

Class is defined as above.

I know that Class(const Class& c) is a copy constructor. It will be called when new Class object is created. For example:

Class c;  // output->running Class()...
Class cc(c); // output->runing Class(const Class& c)...

Now, I want to know when the Class(Class& c) constructor will be called.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Land
  • 171
  • 11
  • _I know that `Class(const Class& c)` is a copy constructor._ `Class(Class& c)` is a copy constructor [as well](http://eel.is/c++draft/class.copy.ctor#1.sentence-1). Const-reference variant is usually preferred (e.g., since copied object is typically not needed to be modified and non-const reference cannot bind const objects nor rvalues). – Daniel Langr Dec 19 '19 at 09:46
  • For the record, I did *not* vote to close this question as a duplicate, contrary to what the note at the top of the post is claiming, and I don’t think it’s a duplicate (though it may be sufficient to help clear up OP’s misunderstanding). – Konrad Rudolph Dec 19 '19 at 09:59
  • If you wish the change the thing being copied as you copy it (e.g., `have_been_copied = true;`) then you want the one without the `const` – Neil Gatenby Dec 19 '19 at 10:00

2 Answers2

1

Both are copy constructor.

class.copy.ctor#1

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments ([dcl.fct.default]). [ Example: X​::​X(const X&) and X​::​X(X&,int=1) are copy constructors.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

I know that Class(const Class& c) is a copy constructor. It will be called when new Class object is created. For example:

Class c;  // output->running Class()...
Class cc(c); // output->runing Class(const Class& c)...

No. Your code actually outputs

running Class()...
running Class(Class& c)...

And there you have it: the non-const copy constructor is called for non-const arguments. That’s all there is to it.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214