PDA

View Full Version : quiz!! what is wrond with the code



seiflotfy
September 22nd, 2005, 12:21 PM
class Number
{
Number (int n)
{
...
}

Number (const Number& n)
{
...
}

Number& operator = (const Number& n)
{
...
}
};

Number n1 (123);

Number n2 (n1);

Number n3 = Number (456);

thumper
September 22nd, 2005, 01:41 PM
class Number
{
Number (int n)
{
...
}

Number (const Number& n)
{
...
}

Number& operator = (const Number& n)
{
...
}
};

Number n1 (123);

Number n2 (n1);

Number n3 = Number (456);
The default visibility of a class is private, so none of your constructors are visible.

LordHunter317
September 22nd, 2005, 03:32 PM
Also, why are you declaring a copy constructor and assignment operator? Unless you're planning on doing deep copies, there is no need. Also, if you're creating a constructor that takes an argument, make sure to use initialization lists to initialize your data.

thumper
September 22nd, 2005, 04:03 PM
Also, why are you declaring a copy constructor and assignment operator? Unless you're planning on doing deep copies, there is no need. Also, if you're creating a constructor that takes an argument, make sure to use initialization lists to initialize your data.
We could also point out that there is nothing in your methods and no main :p

To provide reasoning for the copy stuff that LordHunter317 mentioned, the default is to do a memberwise copy of the member variables, so as long as there are defined copy constructors that have the semantics that you mean, then you don't need to explicitly generate them as the compiler generated ones are normally sufficient. The deep copy mentioned is where you have a pointer, and you want to make a copy of the value being pointed to, not of the pointer itself.

Agree about initializer lists, definately best practice to use them (and necessary at times).

LordHunter317
September 22nd, 2005, 05:52 PM
We could also point out that there is nothing in your methodsActually, I was going to post that it would be nice to post the entire class definition, then thought better of it for some reason and deleted it.


and no main :pNot needed :p

ReiKn
September 23rd, 2005, 08:31 PM
Also, why are you declaring a copy constructor and assignment operator? Unless you're planning on doing deep copies, there is no need. Also, if you're creating a constructor that takes an argument, make sure to use initialization lists to initialize your data.

One might also just want to prohibit copying and assignment for the class by declaring those operators private. But that clearly isn't the case here because operator = is used in the code...

thumper
September 23rd, 2005, 08:46 PM
One might also just want to prohibit copying and assignment for the class by declaring those operators private. But that clearly isn't the case here because operator = is used in the code...
BTW if you are interested in doing this look at boost::noncopyable