Advertisement
bhok

C++ Copy Constructor

Sep 24th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. // More C++ Tutorial at BrandonHok.com
  2.  
  3. #include <iostream>
  4.  
  5. class Copy
  6. {
  7. public:
  8.     Copy(int x = 5, int y = 5); // default constructor
  9.     Copy(const Copy& cp); // copy constructor
  10.     void paste(); // member function
  11. private:
  12.     int x_, y_; // private variables to be declared
  13. };
  14.  
  15. // default constructor definition
  16. Copy::Copy(int x, int y)
  17. {
  18.     x_ = x;
  19.     y_ = y;
  20. }
  21. // copy destructor definition
  22. Copy::Copy(const Copy& cp)
  23. {
  24.     x_ = cp.x_;
  25.     y_ = cp.y_;
  26. }
  27.  
  28. // member function defintion
  29. void Copy::paste()
  30. {
  31.     std::cout << x_ << std::endl << y_ << std::endl;
  32. }
  33.  
  34. int main()
  35. {
  36.     // Try printing the original constructor first
  37.     Copy original;
  38.     original.paste();
  39.  
  40.     // Now we mae a new object and use the copy constructor
  41.     // Basically, all we we did is made a object that copies another
  42.     Copy newNumbers(30, 60);
  43.    
  44.     // Uncomment each method and see how each works!
  45.  
  46.     // method #1 - using assignment operator
  47.     //Copy copier = newNumbers;
  48.    
  49.     // method #2 - passed as a value
  50.     //Copy copier;
  51.     //copier = Copy(newNumbers);
  52.  
  53.     // method #3 - copied explicitly
  54.     //Copy copier(newNumbers);
  55.  
  56.     copier.paste();
  57.  
  58.     system("pause");
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement