When do they get called?
When do they get called?
When does this copy constructor get called? and why..
Code:#include <iostream.h> #include <iomanip.h> int linecount = 1; char label = 'A'; class Data { char ID; int value; public: // Default constructor Data() { ID = label++; value = 0; cout << setw(2) << linecount++ << ": Default Constructor " << ID << " " << value << endl; } // Parametrized Constructor Data(int v) { ID = label++; value = v; cout << setw(2) << linecount++ << ": Parametrized Constructor " << ID << " " << value << endl; } // Copy Constructor Data(const Data &d) { // copy only the value, we get a unique ID ID = label++; value = d.value; cout << setw(2) << linecount++ << ": Copy Constructor " << ID << " " << value << " From " << d.ID << " " << d.value << endl; } // Assignment Operator Data &operator=(Data &d) { // copy only the value value = d.value; cout << setw(2) << linecount++ << ": Assignment of " << ID << " " << value << " From " << d.ID << " " << d.value << endl; return *this; } // Destructor ~Data() { cout << setw(2) << linecount++ << ": Destructor " << ID << " " << value << endl; } }; // A global function which uses Data objects Data Mangle(Data d) { Data temp = d; return temp; } // The main program. int main() { Data a(10); Data b = a; Data c; c = Mangle(a); return 0; }
hmmm
Data b = a;
it copies the members of A into the "this" object.. which is b. Thus the copy constructor is called. oic
but why isnt the assignment operator called..
hahah.. n/m got it.
thx for the help.
Initialization is translated to a copy construction even if in the syntax
type name = existing;
This line has the same effect as
type name(existing);
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
What if the copy constructor was explicit?Initialization is translated to a copy construction even if in the syntax
type name = existing;
This line has the same effect as
type name(existing);
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
Can it be?
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
oh yes.... look
Code:class A { public: explicit A(const A&) {//impl} private: //members }; int main() { A obj; A copy(obj); // fine direct call of cc A copy2 = obj; // error! return 0; }
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
But if it is, can it still be used for arg-by-value? That's an implicit call after all.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law