Using C++ to complete the following program: class Pet { protected: string type;
ID: 3573504 • Letter: U
Question
Using C++ to complete the following program:
class Pet
{
protected:
string type;
string name;
public:
Pet(const string& arg1, const string& arg2);
virtual void describe() const;
virtual string speak() const = 0;
};
class Dog : public Pet
{
public:
void describe() const; // override the describe() function
?
};
class Cat : public Pet
{
?
// Do not override the describe() function
};
ostream& operator<<(ostream& out, const Pet& p)
{
p.describe();
out << "I say " << p.speak();
return out;
}
int main()
{
Dog fido("dog","Fido");
Cat garfield("cat","Garfield");
Pet* ptr = &fido;
cout << *ptr << endl;
ptr = &garfield;
cout << *ptr << endl;
}
OUTPUT
I am an excellent dog and you may refer to me as Fido
I say woof
I am a cat and my name is Garfield
I say meow
Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
class Pet
{
protected:
string type;
string name;
public:
Pet()
{
}
Pet(const string& arg1, const string& arg2)
{ name=arg2;
type=arg1;
}
virtual ~Pet()
{
}
virtual void describe() const
{
}
virtual string speak() const = 0;
};
class Dog : public Pet
{
public:
Dog(const string& arg1, const string& arg2):Pet(arg1,arg2)
{
}
virtual void describe() const// override the describe() function
{
cout<<"I am an excellent dog and you may refer to me as "<<name<<endl;
}
virtual string speak() const
{
return " woof ";
}
};
class Cat : public Pet
{
public:
Cat(const string& arg1, const string& arg2):Pet(arg1,arg2)
{
}
void describe() const
{
cout<<" I am a cat and my name is "<<name<<endl;
}
string speak() const
{
return " meow ";
}
};
ostream& operator<<(ostream& out, const Pet& p)
{
p.describe();
out << "I say " << p.speak();
return out;
}
int main()
{
Dog fido("dog","Fido");
Cat garfield("cat","Garfield");
Pet* ptr = &fido;
cout << *ptr << endl;
ptr = &garfield;
cout << *ptr << endl;
}
========================================================================
Output:
I am an excellent dog and you may refer to me as Fido
I say woof
I am a cat and my name is Garfield
I say meow
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.