0

i am using mingw for c++,i want the compiler to call the copy constructor which is defined by me while returning values. here is the code;

class one

{

public:

    int a;
    one()
    {

    }
    one(int b)
    {
        a = b;
    }
    one(one &ob)
    {
        cout<<"\n copy called";
        a = ob.a;

    }
    ~one()
    {
        cout << "\n dtor called";
    }
    void operator=(one& ob)
    {
        a = ob.a;
    }
};


one func()

{
    one ob(5);

    return ob;
}

int main()

{

    one u=func();
}

the error which i get on running this code is: error: cannot bind non-const lvalue reference of type 'one&' to an rvalue of type 'one'

how to call my own copy constructor while returning values?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 3
    Does this answer your question? https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading. Signature of copy constructor should be `one(const one &ob)` – 463035818_is_not_an_ai Jan 31 '22 at 13:46
  • btw what version of C++ are you using? Starting with C++17 your code should compile (even with the wrong copy constructor) https://godbolt.org/z/vxbGcTGK1 – 463035818_is_not_an_ai Jan 31 '22 at 13:49
  • _"the copy constructor which is defined by me"_ because of a missing `const`, you have not defined a copy constructor. – Drew Dormann Jan 31 '22 at 13:50
  • 1
    @DrewDormann Actually, the `const` is not required. Copy constructors are allowed to take non-const lvalue references, and they're still copy constructors. – cigien Jan 31 '22 at 13:56

0 Answers0