This has been heavily revised. I added a default constructor, an assignment constructor, and an assignment method :
class A
{
public:
int a1 { 0 };
int * b1 { nullptr };
A() {}
A( int x, int y ) {
Set( x, y );
}
A( const A & other ) {
Set( other.a1, * other.b1 );
}
A & operator = ( const A & other )
{
if( this != & other )
{
Set( other.a1, * other.b1 );
}
return *this;
}
void Set( int x, int y ) {
a1 = x;
if( b1 )
delete b1;
b1 = new int( y );
}
};
int main()
{
A a;
A b( 42, 43 );
a = b;
trace( "a.a1 is %d, a.b1 is %d\n", a.a1, * a.b1 );
A c( 56, 57 );
trace( "c.a1 is %d, c.b1 is %d\n", c.a1, * c.b1 );
A d( a );
trace( "d.a1 is %d, d.b1 is %d\n", d.a1, * a.b1 );
return 0;
}
New assignments need to re-allocate the
b1
pointer if there is one so it MUST be initialized appropriately as shown. That is one reason why initialization is so important.
Note how all constructors are routed through the
Set
method. This can be a useful tactic to use, especially if your members are not
public
.
BTW -
trace
is my own output function that I use with GUI programs. You can replace it with
printf
or use
cout
redirection like your were.