Search This Blog

Tuesday, June 9, 2009

Copy Constructor And Assignment Operator

#include <iostream>
using namespace std;

A {
A(){ cout << "default A() called" << endl;}

A(const A& rhs){cout << "copy constructor called\n";}
A& operator=(const A& rhs) { cout << "= operator called\n";}

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) {}


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;

cout << endl;

pass_by_reference_is_faster(a); //will not call copy constructor




1 comment:

Rick Ealno said...

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 -