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