Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ > Problem with co...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 4 Topic 43618 of 47563
Post > Topic >>

Problem with copy constructor

by wyndz0108 <LowieW07m@[EMAIL PROTECTED] > Mar 1, 2008 at 01:36 PM

Hi,

I have this working program (see first program below) that works
without an explicit copy constructor:

//--------------------------- start of first program
-----------------------------//

#include <iostream>

using namespace std;

class Complex
{
   public:
     Complex() { real = 0 ; imag = 0 ; }  		// default constructor
     Complex(int r, int i);                     // convert constructor

     // overload the following operators
     Complex operator - ()  ;     // unary negation

     int real;
     int imag;
};

int main () {

	Complex x(1,8); // input is 1+8i
	Complex z     ; // output should be -1 + -8i

	z=-x;
	cout << z.real << " + " << z.imag <<"i";
}

Complex::Complex(int r, int i): real(r), imag(i) {}

Complex Complex::operator- () {
	return Complex(-real, -imag);
}

// --------------------- end of first program
------------------------- //

The error occurs when I added a copy constructor (see second program
below).

//------------------- start of second program ----------------------//

#include <iostream>

using namespace std;

class Complex
{
   public:
     Complex() { real = 0 ; imag = 0 ; }  		// default constructor
     Complex (Complex &) ;   			// added copy constructor
     Complex(int r, int i);                     // convert constructor

     // overload the following operators
     Complex operator - ()  ;     // unary negation

     int real;
     int imag;
};

int main () {

	Complex x(1,8); // input is 1+8i
	Complex y(x);
	Complex z     ; // output should be -1 + -8i

	z=-x;
	cout << z.real << " + " << z.imag <<"i";
}

Complex::Complex(int r, int i): real(r), imag(i) {}

Complex::Complex(Complex & copy): real(copy.real), imag(copy.imag) {}

Complex Complex::operator- () {
	return Complex(-real, -imag);
}

//------------------------ end of second program
------------------------------//

Please help.

Thank you.
 




 4 Posts in Topic:
Problem with copy constructor
wyndz0108 <LowieW07m@[  2008-03-01 13:36:41 
Re: Problem with copy constructor
Paul Brettschneider <p  2008-03-01 23:04:49 
Re: Problem with copy constructor
Andrey Tarasevich <and  2008-03-01 23:11:08 
Re: Problem with copy constructor
Andrey Tarasevich <and  2008-03-01 23:07:09 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Sun Sep 7 8:24:00 CDT 2008.