-1
using namespace std;

class test {

    public:
        int p;
    test() {
        cout << "base" << endl;
       }
    test(int x) {
        p = new int;* p = x;
        cout<<"args" << endl;
       }
    test(test & args) {
        p = new int;
        *p = *(args.p);
        cout<<“acopy”<< endl; 
       } 
    };

void print(test arg){
    cout <<"funval"<< *(arg.p);
}
void printref(test & arg) {
    cout <<“funref”<< *(arg.p); 
} 
int main() 
{
    test tl;
    test t2 {10};
    test t3 = t2;
    print(t3);
    printref(t2);
    vector < test > myvec;
    myvec.push_back(t2);
    return 0;
}

Hello,

New to c++ here. I am trying to understand the calls of copy constructor with the code below.

My understanding seemed to be be correct till I created a vector of my class test.

When I run the below code , I run into error for line - myvec.push_back(t2)

Error 1:

/usr/include/c++/6/bits/stl_construct.h:75:7: error: invalid initialization of non—const reference of type test&' from an rvalue of type 'test'

Error2:

/usr/include/c++/6/ext/new_allocator.h:120:4: error: b inding 'const test' to reference of type 'test&' disca rds qualifiers { ::new((void *) p) _Up(std::forward<_Args>( args).

I read few articles here and I seem to have found the solution too, as below : Change for copy constructor Test(const test&args)

The thing I am unclear about is the description of errors generated .

  1. In error1 , it says about rvalue. In my pushback call,t2 is an l-val not r-val. Correct? So,which r-val does error talk about?

  2. I also read about push_back call.it’s syntax is: void push_back (const value_type& val); This expects a const type value and I am passing a non-constant which is ok. But I assume, push_back behind the pictures calls copy constructor and then a const value is passed to a non const argument in copy constructor and hence the error?

Can you please help me clarify my understandings here?

Thanks.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
gabbar
  • 49
  • 1
  • 8
  • 2
    Please [edit] your question to include the code copy-pasted *as text*, not as an image. See e.g. [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) as well as http://idownvotedbecau.se/imageofcode – Some programmer dude Mar 19 '21 at 08:09
  • Done.sorry for my ignorance – gabbar Mar 19 '21 at 08:41

1 Answers1

1

Declaring copy constructor with const argument is something you should do, it is expected that this kind of constructor will just use the given value for initialization, hence the name.

  1. The error is about the line which is given in the output, not the push_back itself. So, in the contest of the implementation, it may be L-value or R-value.

  2. Yes, your assumption is correct.

mnikolic
  • 572
  • 1
  • 5
  • 9