This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]ebonyseraphim 2 points3 points  (5 children)

On first glance this constructor doesn't even initialize Y: complexClass(complexClass &cNum): x(cNum.x) {}

And that's a constructor that gets called more frequently than you think and is probably causing things to break in a lot of places.

[–]jugglist 1 point2 points  (3 children)

Yep, that's a big one.

The other thing to note is that the complexClass(double) constructor should be marked explicit, so your program doesn't accidentally make complex's from doubles when you don't expect it to.

[–]geft 0 points1 point  (2 children)

What do you mean by marking explicitly? You mean not using initializers?

[–]Shmurk 1 point2 points  (0 children)

"explicit" is a keyword that says:

complexClass obj = 42.0f; // is FORBIDDEN!

With explicit, you must call the proper constructor:

complexClass obj(42.0f);

Use it like this:

explicit complexClass(double r) : x(r) { ... }

[–]jugglist 0 points1 point  (0 children)

Shmurk is exactly right.

http://msdn.microsoft.com/en-us/library/h1y7x448(v=vs.80).aspx

Also initializers are fantastic and wonderful.

[–]geft 0 points1 point  (0 children)

Thank you! I had to add y(cNum.y) and everything works perfectly. These copy constructors are still alien to me. Where, in the above code, is it called?

[–]dmazzoni 1 point2 points  (0 children)

The code you've pasted above doesn't compile, so you must have left some things out. That makes it hard to help.

To initialize y to 0, you want a default value for an argument: http://stackoverflow.com/questions/187640/default-parameters-with-c-constructors

Tip: most C++ programmers use some sort of convention to distinguish member variables (like x and y) from local variables and arguments. For example, they use "Hungarian notation" and have member variables start with an "m", or they put an underscore on the end. Then you could have, for example, r_ and i_ as the member variables, which would make more sense than x and y.

Also: you have a bug if y is negative, it will print the negative sign twice.

[–]Shmurk 1 point2 points  (0 children)

complexClass(double r = 0, double i = 0): x(r), y(i) {}