0

Hei. I have a question which makes me sad. I selfdefined a normal copy constructor but it does work only when i initialize an object but not when i want to copy values to already existing object. Please look:

class Test {
    public:
        int a;
        int b;

        Test() {
            a=0;
            b=0;
        } // default constructor

        Test(int x,int y): a(x), b(y) {} //constructor number 2

        Test(Test & object): a(object.a*2), b(object.b*2) { }

        // (i multiply times two to see the difference between
        // compilators default copy constructor and my selfdefined - see above)

        void show() { //it shows the current value
            cout << "a:" << a << endl;
            cout << "b:" << b << endl;
        }
};

int main() {
    Test A(2, 4);
    Test B = A; // my copy constructor works **only** while initializing... 
    B.show(); //...so printed values are as i want: B.a=4 B.b=8...
    B = A;//...but now i think my own should be used...
    B.show();//... but is not i thought it should be B.a=4 B.b=8 but
//the default compilers copy constructor is used and: B.a=2 B.b=4 as in     //object A
}

I have loads of questions and theyre more complex than this but its my first one here on this site. Please help me i dont need fast solution you can write a lot in your answer. Thank you.

John Bupit
  • 10,406
  • 8
  • 39
  • 75

1 Answers1

1

In the second case, the assignment operator is used instead of copy constructor. Constructors are used only when initializing objects.

You can also overload assignment operator. You can do it this way:

Test& operator=(const Test &rhs);
Estiny
  • 888
  • 1
  • 7
  • 20
  • Yes thats right im aware of this way. So copy constuct done my way in question have to be replaced with this way you mentioned - you do not know any way to use my cpconstr on already existing object? //Thank you –  Sep 06 '15 at 20:47
  • I've edited my answer - you can do it by overloading an assignment operator. – Estiny Sep 06 '15 at 20:48