I am facing this error while I write this piece of code.
But quite surprisingly the error vanishes when I remove the copy constructor
Would be grateful if someone explains the working of this and the reason why I am getting the error.
#include <iostream>
using namespace std;
class fun
{
public:
fun(int a)
{
cout<<"PARAM"<<endl;
}
fun(fun&p)
{
cout<<"COPY"<<endl;
}
};
int main() {
fun z =fun(100); // error
return 0;
}
#include <iostream>
using namespace std;
class fun
{
public:
fun(int a)
{
cout<<"PARAM"<<endl;
{
fun(fun&p)
{
cout<<"COPY"<<endl;
{
};
int main() {
fun z =fun(100); // error
return 0;
}
[simon@simon-laptop][08:28:03]
[~/tmp/DONTSYNC/hackerrank/otherpeoples]>./compile-latest-cpp.sh
Compiling lamda_cdm_10-blah.cpp
+ g++ -std=c++14 lamda_cdm_10-blah.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
lamda_cdm_10-blah.cpp: In constructor ‘fun::fun(int)’:
lamda_cdm_10-blah.cpp:6:17: warning: unused parameter ‘a’ [-Wunused-parameter]
fun(int a)
^
lamda_cdm_10-blah.cpp: In copy constructor ‘fun::fun(fun&)’:
lamda_cdm_10-blah.cpp:10:17: warning: unused parameter ‘p’ [-Wunused-parameter]
fun(fun&p)
^
lamda_cdm_10-blah.cpp: In function ‘int main()’:
lamda_cdm_10-blah.cpp:16:12: error: cannot bind non-const lvalue reference of type ‘fun&’ to an rvalue of type ‘fun’
fun z =fun(100); // error
^~~~~~~~
lamda_cdm_10-blah.cpp:10:9: note: initializing argument 1 of ‘fun::fun(fun&)’
fun(fun&p)
^~~
+ set +x
Successful
Have the copy constructor take its argument as a reference-to-const:
#include <iostream>
using namespace std;
class fun
{
public:
fun(int a)
{
cout<<"PARAM"<<endl;
}
fun(const fun&p)
{
cout<<"COPY"<<endl;
}
};
int main() {
fun z =fun(100); // error
return 0;
}