Just use the copy constructor and assignment operator. For your class you can get away with using the compiler generated ones. However you'd have to remove your default constructor for that. If you want to see what they'd look like...:
class A
{
public:
A( int n ) : n_( n ) {}
A( const A ©_from ): n_( copy_from.n_ ) {}
A &operator=( const A ©_from )
{
A temp( copy_from );
std::swap( n_, temp.n_ );
return *this;
}
friend std::ostream &operator<<( std::ostream &str, const A &a )
{
return str << a.n_;
}
private:
int n_;
};
int main()
{
A a( 5 ), b( 4 );
std::cout << a << std::endl << b << std::endl;
a = b;
std::cout << a << std::endl << b << std::endl;
}
Note that the assignment operator is a bit more complicated that it needs to be - I tend to write them like that these days to keep them exception safe when the class gets more complicated.
In response to Volodya's comment below...
Another benefit of the "copy and swap" style of assignment operator is that you don't need to check for self assignment. If you look at older C++ texts (pre-1999 or so when the idiom was used as part of the solution to Tom Cargill's "aaarrggghhh, exceptions break everything!" challenge) you'll see assignment operators written like this:
A &operator=( const A ©_from )
{
if( ©_from != this )
{
n_ = copy_from.n_;
}
return *this;
}
The idea here was to make sure that when you're dealing with pointer members and you don't do something daft like:
A a( 10 );
a = a;
you won't cause a memory leak or end up double referencing an object or a deleted object. (It's more likely this will happen through through an alias, not many of us are daft enough to do it directly).
Copy and swap removes that requirement. If you follow the code you'll see that all data is copied first which deals with allocating and copying new sub-objects. After the old contents of the object are swapped with the temporary the temporary's destructor cleans up any sub objects from the original object. So the copy step handles allocating new sub objects, the swap step handles freeing old sub objects.
Cheers,
Ash