Copy initialization, Copy constructor

#include <iostream>

class Foo {
public:
    Foo(int x) : m_x(x) {
        std::cout << "Constructor called with value: " << x << std::endl;
    }

private:
    int m_x;
};

int main() {
    Foo bar1(10);  // Direct initialization
    Foo bar2 = 20; // Copy initialization (actually calls the constructor)

    return 0;
}        

Generally, Class Objects are created like "Foo bar1(10);"

I come across the initializing the object like "Foo bar2 = 20;", which is unusual. I got the question that Why programmer would do like this and How the compiler do the compile check.

Creating an object like Foo bar2 = 20; is an example of copy initialization in C++. It is syntactic sugar that allows an object to be initialized in a more concise way.

Copy Initialization:

This may appear to be assigning 20 to bar2, but it’s actually using the constructor Foo(int x) to initialize bar2 with the value 20.

This syntax is consistent with how built-in types are initialized.

For example, when "int i = 10;" is ok for the compiler why not "Foo bar2 = 20;"

In older versions of C++, there were certain contexts where copy initialization was necessary or preferred. Modern C++ has evolved.

To prevent copy initialization use "explicit" prefix to the constructor,

class Foo {
public:
    explicit Foo(int x) : m_x(x) {
        std::cout << "Constructor called with value: " << x << std::endl;
    }

private:
    int m_x;
};        

Copy Constructor:

One more instance is where we use copy initialization style is during copy constructor.

class Foo {
public:
    // Parameterized constructor
    Foo(int x) : m_x(x) {
        std::cout << "Parameterized constructor called with value: " << x << std::endl;
    }

    // Copy constructor
    Foo(const Foo &other) : m_x(other.m_x) {
        std::cout << "Copy constructor called with value: " << other.m_x << std::endl;
    }

    // Function to display the value
    void display() const {
        std::cout << "Value: " << m_x << std::endl;
    }

private:
    int m_x;
};

int main() {
    Foo bar1(10);  // Parameterized constructor is called
    Foo bar2 = bar1;  // Copy constructor is called in copy initialization style

    std::cout << "bar1: ";
    bar1.display();
    std::cout << "bar2: ";
    bar2.display();

    return 0;
}        



要查看或添加评论,请登录

M Vijaynath的更多文章

社区洞察

其他会员也浏览了