objects iii you should have a dog class that supports
play

Objects III You should have a dog class that supports energy. - PowerPoint PPT Presentation

Objects III You should have a dog class that supports energy. Playing fetch decreases a dog's energy, sleeping increases it. Start with your code from last time, or get feb-24-start.cpp. Warmup : Fill in the sleep method. This method


  1. Objects III

  2. • You should have a dog class that supports energy. Playing fetch decreases a dog's energy, sleeping increases it. • Start with your code from last time, or get feb-24-start.cpp. • Warmup : Fill in the sleep method. This method should let the dog sleep for a certain number of hours, and increases their energy by that amount. • Fill in the chase method. Add a method chase(dog & buddy) to your class. This method will let your dog chase another dog. A dog can only chase another if both dogs’ energies are above zero! Inside the method, print a message with both dogs' names. This method should decrease both dogs' energies by 1. • Hint : Inside a class, you have access to your own object's private variables, plus private variables of other objects that are passed in as arguments!

  3. Constructors and destructors • A constructor (abbrev ctor ) is a method that is run automatically when an object is created. • A destructor (abbrev dtor ) is a method that is run automatically when an object is "destroyed." – For all objects right now, this means when the object goes out of scope.

  4. Constructors • Constructors are commonly used to initialize the fields (variables) in a class to appropriate values. • Without constructors, the user would have to set all the fields in a class by hand after each object creation. • The name of a constructor is always the same name as the class itself.

  5. Dog default constructor • What are appropriate values to initialize each field to in our dogs?

  6. Dog constructors • Classes can have multiple constructors. • The default constructor never takes any arguments, but other constructors can. • These arguments are typically used to set the fields of the class.

  7. Destructors • The name of a destructor is always the same name as the class, prefaced with a ~ (tilde). – Destructors never have any arguments, and there can be only one per class.

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend