Question

In Exercise 1, displayAnimal uses an Animal reference variable as its parameter. Change your code to...

In Exercise 1, displayAnimal uses an Animal reference variable as its parameter. Change your code to make the displayAnimal function anim parameter as an object variable, not a reference variable. Run the code and examine the output. What has changed?

Polymorphic behavior is not possible when an object is passed by value. Even though printClassName is declared virtual, static binding still takes place because anim is not a reference variable or a pointer.

Alternatively we could have used an Animal pointer in the displayClass function. Modify your code to make the animparameter a pointer and verify that it now works as expected. Now use the pointer parameter to call the printClassName member function:

anim->printClassName();

Similarly, pointers to a base class may be assigned the address of a derived class object. Add the statement to dynamically allocate a Dog object and assign its address to an Animal pointer named ptrAnimal. Use the pointer to call the printClassName member function in your main function like this:

   Animal *ptrAnimal = new Dog();
   ptrAnimal->printClassName();

We can create an array of Animal pointers, some of which point to Cat objects and some point to Dog objects. Using a loop we can step through the array testing each element by calling the displayAnimal function. Add this code to create a driver program that tests multiple types of objects:

   // Constant for the size of an array.
   const int NUM_TESTS = 4;

   // tests is an array of Animal pointers.
   // Each element of tests is initialized with the
   // address of a dynamically allocated object.
   Animal *tests[NUM_TESTS] =
   { new Dog(),
       new Cat(),
       new Dog(),
       new Cat()
   };

   // Display the class type for each element in the array.
   for (int count = 0; count < NUM_TESTS; count++)
   {
       cout << "Animal #" << count + 1 << endl;
       displayAnimal(tests[count]);
       cout << endl;
   }

================================================================================================

#include

#include

using namespace std;

// Animal is a base class.

class Animal

{

public:

// Constructor

Animal()

{ }

virtual void printClassName() const

{

cout << "Animal";

}

};

// The Dog class is derived from Animal

class Dog : public Animal

{

public:

// Constructor

Dog()

{ }

void printClassName() const

{

cout << "Dog";

}

};

// The Cat class is derived from Animal

class Cat : public Animal

{

public:

// Constructor

Cat()

{ }

void printClassName() const

{

cout << "Cat";

}

};

//*************************************************

// displayAnimal function *

//*************************************************

void displayAnimal(Animal &anim)

{

cout << "This animal is a ";

anim.printClassName();

cout << "." << endl;

}

//*************************************************

// main function *

//*************************************************

int main()

{

Cat myCat;

Dog myDog;

cout << "Calling printClassName member functions." << endl;

cout << "Cat: ";

myCat.printClassName();

cout << endl << "Dog: ";

myDog.printClassName();

cout << endl << endl << "Using function displayClass:" << endl;

displayAnimal(myCat);

displayAnimal(myDog);

system("PAUSE");

return 0;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

If you have any doubts, please give me comment...

#include <iostream>

#include <string>

using namespace std;

// Animal is a base class.

class Animal {

public:

// Constructor

Animal() {}

virtual void printClassName() const { cout << "Animal"; }

};

// The Dog class is derived from Animal

class Dog : public Animal {

public:

// Constructor

Dog() {}

void printClassName() const { cout << "Dog"; }

};

// The Cat class is derived from Animal

class Cat : public Animal {

public:

// Constructor

Cat() {}

void printClassName() const { cout << "Cat"; }

};

//*************************************************

// displayAnimal function *

//*************************************************

void displayAnimal(Animal *anim) {

cout << "This animal is a ";

anim->printClassName();

cout << "." << endl;

}

//*************************************************

// main function *

//*************************************************

int main() {

// Constant for the size of an array.

const int NUM_TESTS = 4;

// tests is an array of Animal pointers.

// Each element of tests is initialized with the

// address of a dynamically allocated object.

Animal *tests[NUM_TESTS] = {new Dog(), new Cat(), new Dog(), new Cat()};

// Display the class type for each element in the array.

for (int count = 0; count < NUM_TESTS; count++) {

cout << "Animal #" << count + 1 << endl;

displayAnimal(tests[count]);

cout << endl;

}

return 0;

}

Add a comment
Know the answer?
Add Answer to:
In Exercise 1, displayAnimal uses an Animal reference variable as its parameter. Change your code to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create a base class and two derived classes. Also, create and call a member function named...

    Create a base class and two derived classes. Also, create and call a member function named communicate() that behaves differently when called by each class. Create a single C++ project (and CPP source file) named animal_communication as follows: Into this source, type the source code for Program 15-16, "Program Output," in Section 15.6, "Polymorphism and Virtual Member Functions," in Ch. 15, "Inheritance, Polymorphism, and Virtual Functions," of Starting Out With C++ From Control Structures Through Objects. Run and debug the...

  • Please submit the following files for this assignment: *****************Animal.h, Animal.cpp, Mammal.h, Mammal.cpp, Cat.h, Cat.cpp, main.cpp********* Assignment...

    Please submit the following files for this assignment: *****************Animal.h, Animal.cpp, Mammal.h, Mammal.cpp, Cat.h, Cat.cpp, main.cpp********* Assignment 4 – OOP – inheritances Create a base class Animal (Animal.h, Animal.cpp) Member variables (private): string name; string type; Member methods (public): Constructor(s) Setters Getters eat(); //display “Eat food.” Create a derived class Mammal from Animal (public) (Mammal.h, Mammal.cpp) Member variables (private): string hair_type; //eg: fur, hair,etc Member methods (public): Constructor(s) Setters Getters Create a derived class Cat from Mammal (public) (Cat.h, Cat.cpp) Member...

  • previous assignment code /*C++ test program to test the classes, Animal, Mammal and Cat and print...

    previous assignment code /*C++ test program to test the classes, Animal, Mammal and Cat and print the results on console window.*/ //Main.cpp //include header files #include<iostream> //include Animal, Mammal and Cat header files #include "Animal.h" #include "Mammal.h" #include "Cat.h" using namespace std; int main() {    //create Animal object    Animal animal("Dog","Mammal",4);    cout<<"Animal object details"<<endl;    cout<<"Name: "<<animal.getName()<<endl;    cout<<"Type: "<<animal.getType()<<endl;    cout<<"# of Legs: "<<animal.getLegs()<<endl;          cout<<endl<<endl;    //create Cat object    Cat cat("byssinian cat","carnivorous mammal",4,"short...

  • Given the following code: #include <iostream> #include <iomanip> using namespace std; class Animal{ private: int height;...

    Given the following code: #include <iostream> #include <iomanip> using namespace std; class Animal{ private: int height; int weight; public: void setHeight(int h){ height = h; } int getHeight(){ return height; } void setWeight(int w){ weight = w; } int getWeight(){ return weight; } virtual void makeSound() = 0; virtual void eat(); }; class Dog: public Animal{ public: void makeSound(){ cout << "Bow Bow\n"; } void eat (){ cout <<"The dog is eating\n"; } void Catch(){ cout << "The dog is...

  • C++ 1. The copy constructor is used for one the following scenarios: I. Initialize one object...

    C++ 1. The copy constructor is used for one the following scenarios: I. Initialize one object from another of the same type. II. Copy an object to pass it as argument to a function. III. Copy an object to return it from a function. Read the following program and answer questions (20 points) #include <iostream> using namespace std; class Line public: int getLength( void); Line( int len // simple constructor Line( const Line &obj) 1/ copy constructor Line (); //...

  • This is the question about object-oriend programming(java) please show the detail comment and prefect code of...

    This is the question about object-oriend programming(java) please show the detail comment and prefect code of each class, Thank you! This question contain 7 parts(questions) Question 1 Create a class a class Cat with the following UML diagram: (the "-" means private , "+" means public) +-----------------------------------+ | Cat | +-----------------------------------+ | - name: String | | - weight: double | +-----------------------------------+ | + Cat(String name, double weight) | | + getName(): String | | + getWeight(): double | |...

  • #code for creature.cpp #include <iostream> using namespace std; class Creature { public: Creature(); void run() const;...

    #code for creature.cpp #include <iostream> using namespace std; class Creature { public: Creature(); void run() const; protected: int distance; }; Creature::Creature(): distance(10) {} void Creature::run() const { cout << "running " << distance << " meters!\n"; } class Wizard : public Creature { public: Wizard(); void hover() const; private: int distFactor; }; Wizard::Wizard() : distFactor(3) {} void Wizard::hover() const { cout << "hovering " << (distFactor * distance) << " meters!\n"; } //Created new derived class from Creature class Widget...

  • Ship, CruiseShip, and CargoShip Classes (in C++ language i use visual studios to code with) design...

    Ship, CruiseShip, and CargoShip Classes (in C++ language i use visual studios to code with) design a Ship class that has the following members: - A member variable for the name of the ship (a string) - A member variable for the year that the ship was built (a string) - A contsructor and appropriate accessors and mutators - A virtual print function that displays the ship's name and the year it was built (nobody seems to get this part...

  • Question 1 2 pts The preprocessor executes after the compiler. False True Question 2 2 pts...

    Question 1 2 pts The preprocessor executes after the compiler. False True Question 2 2 pts What code is human-readable and follows the standards of a programming language? Secret code Source code Key code None of these Machine code Question 3 2 pts What is the symbol that marks the beginning of a one line comment? Question 1 2 pts The preprocessor executes after the compiler. True False Question 5 2 pts A statement that may be used to stop...

  • Can you turn this code into a C++ class diagram? Animals.h #1 fndef ANIMALS-H #define ANIMALSH...

    Can you turn this code into a C++ class diagram? Animals.h #1 fndef ANIMALS-H #define ANIMALSH #include <string> class Animal { - public: Animal (const std::string&name: fName( name virtual void Speak O const0 th protected: std::string fName; !; // class Animal class Dogpublic Animal public: Dog (const std::string& nameAnimal ( name virtual void SpeakO const; //class Dog class Cat public Animal f public: Cat ( const std::string& nameAnimal(name) t virtual void Speak O const; 1; // class Cat class Tiger:public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT