Inheritance and Polymorphism
The goal of this lab is to give you a bit more experience with inheritance and polymorphism. Complete the steps below:
- Create a new Project and add the following pieces of code to the project: pet.h - dog.h - test.cpp. Note: You will need to complete steps 2 and 3 before you can compile this code.
- In order to use dynamic_cast you will need to enable the use of runtime type information.
- From the menu, select Project and then Settings.
- Select the C/C++ Tab.
- From the Category pull-down menu select C++ Language.
- Check Enable Run-Time Type Information (RTTI).
- Click OK.
- Fix the errors in test.cpp. Refer to your exam to determine which lines will not compile and comment out those lines.
- Build and run test.cpp.
- Remove the virtual keyword from dog.h and pet.h and build your project.
- Replace the virtual keyword.
- Add the following lines between the last cout and the return in main:
Pet* p2_ptr = new Pet("Jake", "Spotted");
Dog* d2_ptr = dynamic_cast<Dog*>(p2_ptr);
cout << d2_ptr->getBreed() << endl;
- Build and run test.cpp.
Email me (srollins@mtholyoke.edu) answers to the following questions by Friday, 3/10/06 - 5pm. Note: I expect your answers to demonstrate a thorough understanding of each concept. You need to think carefully about why you get the output or errors that you get.
- Explain what happened at step 5.
- Explain what you think the three lines of code you added in step 7 should accomplish.
- Explain what happened at step 8.
- Give three examples of classes (other than Dog), that might inherit from Pet. For each, outline at least one additional data member for the class. This is a design question; it does not require any implementation.
- Do you think it would ever make sense to have a class that would inherit from Dog? If so, give an example and describe what the class would look like. If not, argue why not.
Sami Rollins