/* main.cpp */ #include #include #include using namespace std; class Book { int cost; string author; int size[2]; public: Book(){}; //Default constructor Book(int c, string a, int *s); ~Book() { cout << "destructor" << endl;} //destructor Book(const Book&); //copy constructor friend ostream& operator<<(ostream& who, Book& what) { who << what.author << " " << what.cost << " " << what.size[0] << " " << what.size[1]; return who; } }; Book::Book(int c, string a, int *s): cost(c), author(a) {size[0] = *s; size[1] = *(s+1);} // Copy constructor: not needed - just here so you see when it is invoked Book::Book(const Book& p): cost(p.cost), author(p.author) { size[0] = p.size[0]; size[1] = p.size[1]; cout << "Copy Constructor: " << author << ' ' << cost << endl; } void moo(Book x) // x is passed by value, i.e. its mode is "in" { int s[] = {1, 2}; Book y(12, "Poe", s); x = y; // "destructor" is printed once for deletion of y // and once for deletion of x (passed by copying) } void foo(Book& x) // x is passed by reference, its mode is "out" { int s[] = {1, 2}; Book y(15, "Roth", s); x = y; // "destructor" is printed once for deletion of y } int main () { Book a; //default constructor - a is with undefined values of cost and author int ss[2] = {7, 11}; Book b(7, "Tolstoy", ss);//default constructor a = b; // assignment is componentwise cout << a << endl; moo(a); //copy constructor cout << a << endl; foo(a); //parameter is passed by reference cout << a << endl; //"destructor" is printed out twice, once for a, once for b return 0; }