You are given the following segment of code. All the following C++ questions are
ID: 3721368 • Letter: Y
Question
You are given the following segment of code. All the following C++ questions are based on this code.
class Owner {
public: int iPhone;
string sEmail;
Owner(int phone, string email) { // constructor
iPhone = phone; sEmail = email;
}
};
class Pet {
public: string sName;
Owner *pOwner;
Pet(string name, int phone, string email) { // constructor
sName = name; pOwner = new Owner(phone, email);
}
};
class Cat : public Pet {
public: string cBreed;
int iAge;
Cat(string name, int phone, string email, string breed, int age) . . . // write the constructor
};
class PetNode {
public: PetNode *pNext;
Pet *pNode;
PetNode() { pNode = NULL; pNext = NULL; };
} *head = NULL; // head is the global pointer to the PetNode linked list
void insertPet();
void insertCat();
//...
void main(void) {
Pet* p;
Cat* c;
PetNode* pn;
// input the data here
insertPet(…);
insertCat(…);
// ...
}
The following diagrams show the relationships among the classes and an example of the linked list constructed using the classes.
1. Write the insertCat function to insert a Cat object into the linked list (whose nodes are of PetNode type). The start pointer of the linked list is head pointer. Insert the new node at the end of the linked list (as the last node). You do not have to write "Get" and "Set" functions to access the members of any class. You can directly access them. You can assume that the required input data are entered in the main program before calling the insertCat method. [7 points]
void insertCat(char *name, int phone, char *email, string breed, int age)
The following diagrams show the relationships among the classes and an example of the linked list constructed using the classes PetNode pNext pNode PetNode pNext pNode PetNode NULL pNode head Pet Owner containment sName - iPhone Pet powner- sEmail Pet CName inheritance cName pOwner sBreed pOwner pOwner sBreedOwner Age iPhone iPhone iPhone Age cEmail cEmail cEmailExplanation / Answer
void insertCat(char *name, int phone, char *email, string breed, int age) { std::string nameStr(name); std::string emailStr(email); // create a cat object Cat *cat = new Cat(nameStr, phone, emailStr, breed, age); // create new node of linkedlist objetc, using the cat above // as Cat is a Pet, we can create the petnode object using Cat PetNode *newNode = new PetNode(); newNode->pNode = cat; newNode->pNext = null; // if head is null, then this node is the first one in list // we just need to assign it to head. if(head == NULL) { head = newNode; } else { // find the last node PetNode *start = head; while(start->pNext != NULL) { start = start->pNext; } // attach new node to the last node's next pointer start->pNext = newNode; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.