-1

I am learning C++ and come across this question when learning the use of constructors. Consider the snippet below:

#include <string>
#include <iostream>

using namespace std;

class Foo
{
public:
    Foo() { m_ = 0; cout << "default ctor called." << endl; }
    Foo(int a) { m_ = 1; cout << "int ctor called." << endl; }
    Foo(string str) { m_ = 2; cout << "str ctor called." << endl; }
    Foo(Foo& f)
    {
        cout << "copy ctor called." << endl;
        m_ = f.m_;
    }

    Foo& operator=(string str)
    {
        cout << "= operator called." << endl;
        m_ = 3;
        return *this;
    }

    int m_;
};


int main()
{
    Foo f1 = 100;
    cout << f1.m_ << endl;

    Foo f2 = "ya";
    cout << f2.m_ << endl;

    Foo f3("ha");
    cout << f3.m_ << endl;

    f1 = "hee";
    cout << f1.m_ << endl;

    Foo f4 = Foo();
    cout << f4.m_ << endl;

    return 0;
}

I realize that

Foo f1 = 100;

Foo f2 = "ya";

actually calls the constructors as if I am doing

Foo f1(100);

Foo f2("ya");

I fail to find any relevant explanation on this. Can anyone please explain what is going on here? The following thread is close to mine but doesn't answer exactly my question. C++ Object Instantiation vs Assignment

1 Answers1

2

The Foo object is constructed from value assigned to object (implicit conversation)

Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2

where it is used in this context. Then copy-initializtion initializes an object from another object (constructed via implicit conversation as mentioned before)

You can disable it (only for this constructor) by using explicit keyword.

explicit Foo(int a)

Which makes this operation

Foo f1 = 100;

illegal.

kocica
  • 6,412
  • 2
  • 14
  • 35
  • That doesn't disable copy initialisation. It disables conversion from an `int` to a `Foo`. –  Aug 30 '17 at 17:19
  • It doesn't directly disable copy initialization. It's just that explicit constructors are not considered for copy initialization. – Rakete1111 Aug 30 '17 at 17:21
  • Disabling copy initialisation would not allow `Foo f; Foo g = f;`, which your code does not. –  Aug 30 '17 at 17:23
  • Well, you have now completely re-written your answer, so these comments are moot. –  Aug 30 '17 at 17:26
  • Yes iam not good english speaker so you were right. We may remove these comments now. Anyway thank you. – kocica Aug 30 '17 at 17:28
  • 1
    I have apparently mixed up the concept of assignment and initialization. After using the right key word, I can find a lot more resources. Thank you very much. – Larry Liang Aug 31 '17 at 02:14