#include <iostream>
using namespace std;
class A {
public:
A(){ cout << "default A() called" << endl;}
A(const A& rhs){cout << "copy constructor called\n";}
A& operator=(const A& rhs) { cout << "= operator called\n";}
};
void pass_by_reference_is_faster(A& obj) {}
//pass by value, forcing copy constructor to call to make a copy of A
void will_make_a_copy_with_copy_constructor(A obj) {}
void test_A()
{
A a;
A a2;
cout << "before a2=a \n";
a2 = a; //this will call operator=
cout << "before A a3 = a2 \n";
A a3 = a2; // this will call copy constructor;
// why? faster, so we don't call A(), make all
// member variables uninitialized/default
// , and THEN assign
// INSTEAD, upon creation, we get all values ready
// this will make a big difference if A is complex
cout << endl;
will_make_a_copy_with_copy_constructor(a);
cout << endl;
pass_by_reference_is_faster(a); //will not call copy constructor
}
int main()
{
test_A();
}
Search This Blog
Tuesday, June 9, 2009
Copy Constructor And Assignment Operator
Subscribe to:
Post Comments (Atom)
1 comment:
Well, the use of copy constructors and destructors should never result in error. Handling errors is a tedious job, but honestly, errors tell you that your program is incorrect. There are lots of concepts to learn in exception handling, and I found this website really helpful in improving my knowledge - http://mortoray.com/2013/12/05/is-exception-safe-code-truly-possible/
Post a Comment