{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Assignment operator and copy constructor are similar

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: uctor body •  Compiler generated default constructor: Book::Book(){//empty body} Book aBook(); •  /tle: empty string, which is ini/alized by the STL string class •  year: garbage Assignment Operator= •  Assign an object of a class type to another object of the same class. •  Assignment operator and copy constructor are similar, in that they both perform member ­ wise copy from one object to another. •  Difference: assignment operator overwrites object on the le] ­hand ­side of =, while copy constructor ini/alizes the object value the first /me. • Assigned object has to exist previously. Book& Book::operator= (const Book& rhs) { //check for selfassignment if(&rhs != this){ title=rhs.title; year=rhs.year; } return *this; } Programmer Defined Constructors //Book.cc #include “Book.h” //default constructor Book::Book():year(0){} //copy constructor, same as //the compiler generated one Book::Book(const Book& aBook) { title=aBook.title; year=aBook.year; } //constructor with parameters Book::Book(string title_in, int year_in) { title=title_in; year=year_in; } int main(){ //use default constructor Book a; //use the constructor with parameter Book b("C", 1990); //use copy constructor Book c=b; //use assignment operator= b=a; //use ? c=a.swap(b); } c=a.swap(b); •  Passing object parameter: –  involves co...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online