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
  • 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 (); //...

  • 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...

  • Variable Size Array with Classes, Testing. Study Code and Object Definition Windows of Microsoft ...

    Variable Size Array with Classes, Testing. Study Code and Object Definition Windows of Microsoft Visual Studio described here. As you work on the below project, demonstrate to the instructor the usage of this feature. Create a project titled Lab11_VarArrayTest. Implement the dynamically expanding and contracting array of doubles described in the previous lab as a class. You should use this class definition. The class attributes are a pointer to the dynamically allocated array dAarray and the array size size This...

  • Answer this in c++ #include <iostream> #include <fstream> #include <string> using namespace std; class Person {...

    Answer this in c++ #include <iostream> #include <fstream> #include <string> using namespace std; class Person { public: Person() { setData("unknown-first", "unknown-last"); } Person(string first, string last) { setData(first, last); } void setData(string first, string last) { firstName = first; lastName = last; } void printData() const { cout << "\nName: " << firstName << " " << lastName << endl; } private: string firstName; string lastName; }; class Musician : public Person { public: Musician() { // TODO: set this...

  • 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...

  • 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...

  • Here is the code from the previous three steps: #include <iostream> using namespace std; class Student...

    Here is the code from the previous three steps: #include <iostream> using namespace std; class Student { private: //class variables int ID; string firstName,lastName; public: Student(int ID,string firstName,string lastName) //constructor { this->ID=ID; this->firstName=firstName; this->lastName=lastName; } int getID() //getter method { return ID; } virtual string getType() = 0; //pure virtual function virtual void printInfo() //virtual function to print basic details of a student { cout << "Student type: " << getType() << endl; cout << "Student ID: " << ID...

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
ADVERTISEMENT