Re: Operator New help
john wrote:
.....
---------------------------------------
I changes the code to the following, and their is a parse error?
in the line
B(const B& copy) a( new A(* copy.a) )
B and a are both making a copy??
OK - this should give you a better idea - when playing/learning about
C++ objects it's usually good to output a message at the constructor and
destructor just to get a good idea of what happens when.
I compiled this below so it should compile on your system as well
#include <string>
#include <iostream>
using namespace std;
const bool doecho = true;
template <typename T>
void Echo( T * obj, const std::string & str )
{
if ( doecho )
{
cerr << "Echo (" << obj << ") - " << str << "\n";
}
}
class A
{
int n;
public:
A()
: n()
{
Echo( this, "Default construct A" );
}
A( int x )
: n(x)
{
Echo( this, "Construct A(int)" );
}
// A( const A& ) ... normally use default copy constructor
A( const A & ia )
: n( ia.n )
{
Echo( this, "Construct A( const A& )" );
}
~A()
{
Echo( this, "~A()" );
}
void print()
{
cout << n << "\n\n";
}
};
class B
{
A * a;
public:
// all constructors should new an A
B(const A & x)
: a( new A(x) ) // initialize with an A - make a new A here
{
Echo( this, "Construct B(const A&)" );
}
B(const B & copy)
: a( new A(* copy.a) ) // deep copy the A
{
Echo( this, "Construct B(const B&)" );
}
B & operator=(const B & x)
{
Echo( this, "B::operator =(const B&) - start" );
// need to make a new A from the B coming in
// and we need to delete the A that is currently
// being pointed to
// make this thread safe
// new can throw so make it so things can recover
A * pa( a );
// the "new" A pointer replaces the old A pointer
a = new A( * x.a );
// we didn't throw - delete the old A object
delete pa;
Echo( this, "B::operator =(const B&) - end" );
// assignment should always return one-self
return *this;
}
// the destructor should delete the A new()ed in the
// constructor or the assignment operator
~B()
{
Echo( this, "~B() - start" );
delete a;
Echo( this, "~B() - end" );
}
void print ()
{
a->print();
}
};
//---------------------------------------------------------------------------
int main()
{
A a(5);
B b = a;
{
A a1(7);
B b1 = a1;
b = b1;
}
b.print();
cout << endl;
int trick;
cin >> trick;
return 0;
}