HELP ON C++ CODE

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;
}

Your curly braces are all unbalanced:

#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;
                    }

Please post your actual, formatted code.

Oh , my bad ! but the error is in the line i have mentioned , its just that i have copied it wrongly

Well, copy it rightly :slight_smile: There’s no point trying to guess what’s wrong from wrongly-pasted code.

yeah done it :sweat_smile:

1 Like

Thanks :slight_smile:

[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;
}

Thanks @ssjgz that helped ,but can you explain to me why writing ‘const’ fixes the whole problem? Want to have my concepts clear :sweat_smile:

I don’t have much time at the moment as I have to get to work, but look up:

Copy Initialisation, which is what that line is doing; and read this.

1 Like