fork download
  1. #include <iostream> // for cout and cin
  2. using namespace std;
  3.  
  4. class Cat // begin declaration of the class
  5. {
  6. public: // begin public section
  7. Cat(int initialAge); // constructor
  8. Cat(const Cat& copy_from); //copy constructor
  9. Cat& operator=(const Cat& copy_from); //copy assignment
  10. ~Cat(); // destructor
  11.  
  12. int GetAge() const; // accessor function
  13. void SetAge(int age); // accessor function
  14. void Meow();
  15. private: // begin private section
  16. int itsAge; // member variable
  17. char * string;
  18. };
  19.  
  20. // constructor of Cat,
  21. Cat::Cat(int initialAge)
  22. {
  23. this->itsAge = initialAge;
  24. string = new char[10]();
  25. }
  26.  
  27. //copy constructor for making a new copy of a Cat
  28. Cat::Cat(const Cat& copy_from) {
  29. this->itsAge = copy_from.itsAge;
  30. this->string = new char[10]();
  31. std::copy(copy_from.string+0, copy_from.string+10, string);
  32. }
  33.  
  34. //copy assignment for assigning a value from one Cat to another
  35. Cat& Cat::operator=(const Cat& copy_from) {
  36. this->itsAge = copy_from.itsAge;
  37. std::copy(copy_from.string+0, copy_from.string+10, string);
  38. }
  39.  
  40. Cat::~Cat() // destructor, just an example
  41. {
  42. delete[] string;
  43. }
  44.  
  45. // GetAge, Public accessor function
  46. // returns value of itsAge member
  47. int Cat::GetAge() const
  48. {
  49. return itsAge;
  50. }
  51.  
  52. // Definition of SetAge, public
  53. // accessor function
  54.  
  55. void Cat::SetAge(int age)
  56. {
  57. // set member variable its age to
  58. // value passed in by parameter age
  59. this->itsAge = age;
  60. }
  61.  
  62. // definition of Meow method
  63. // returns: void
  64. // parameters: None
  65. // action: Prints "meow" to screen
  66. void Cat::Meow()
  67. {
  68. cout << "Meow.\n";
  69. }
  70.  
  71. // create a cat, set its age, have it
  72. // meow, tell us its age, then meow again.
  73. int main()
  74. {
  75. int Age;
  76. cout<<"How old is Frisky? ";
  77. cin>>Age;
  78. Cat Frisky(Age);
  79. Frisky.Meow();
  80. cout << "Frisky is a cat who is " ;
  81. cout << Frisky.GetAge() << " years old.\n";
  82. Frisky.Meow();
  83. Age++;
  84. Frisky.SetAge(Age);
  85. cout << "Now Frisky is " ;
  86. cout << Frisky.GetAge() << " years old.\n";
  87. return 0;
  88. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
How old is Frisky? Meow.
Frisky is a cat who is 11101 years old.
Meow.
Now Frisky is 11102 years old.