Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which way is preferred to call copy constructor for a class?

Below is sample class written with copy constructor in c++.

class Foo {
public:
    Foo()   { std::cout << "Foo::Foo\n";}
    ~Foo()   { std::cout << "Foo::Foo\n";}
    Foo(const Foo& rhs) {
        std::cout << "cctor\n";
    }

    Foo& operator=(const Foo& rhs) {
        if (&rhs == this) return *this;
        std::cout << " operator =\n";
        return *this;
    }

    void bar() { std::cout << "Foo::bar\n";}
};

Now we can write in couple of ways which would invoke copy constructor of the class.

Foo x;
Foo y;
Foo z = x;     // This calls copy constructor
Foo a(z);      // This also calls copy constructor

So out of two style which one is preferred and is there any explanation for that?. Or these two are more of style preference of developer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

out of two style which one is preferred

Foo z = x; is copy initialization vs Foo A(z); is direct initialization. If you understand the difference between the two, you will be able to decide which is suitable in which situation. There is no one fits all in c++. Asking which is preferred assumes that one of them is "always" preferred over the other, which is not the case in reality. Depending on the context one might be preferred over the other.

For example, direct initialization would work even when the copy constructor is explicit while copy initialization would not work there. In implicit conversions where copy initialization is performed, the explicit copy ctor won’t be used.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading