Respuesta :
The question involves basic polymorphism. The following is the partial flow of the program.
baseItemPtr = new BaseItem();
baseItemPtr.setLastName("Smith");
derivedItemPtr = new DerivedItem();
derivedItemPtr.setLastName("Jones");
derivedItemPtr.setFirstName("Bill");
itemList.add(baseItemPtr);
itemList.add(derivedItemPtr);
for (i = 0; i < itemList.size(); ++i) {
itemList.get(i).printItem();
}
return;
baseItemPtr = new BaseItem();
baseItemPtr.setLastName("Smith");
derivedItemPtr = new DerivedItem();
derivedItemPtr.setLastName("Jones");
derivedItemPtr.setFirstName("Bill");
itemList.add(baseItemPtr);
itemList.add(derivedItemPtr);
for (i = 0; i < itemList.size(); ++i) {
itemList.get(i).printItem();
}
return;
To print the last name as smith, first and last name as bill jones, use the polymorphism property of OOPs. For this, define a base class and derive the child class from the base class that have the same property as base class have. Set the last name as given name and in the child class assign this value to first name. By using pointer one can call the values. Here I have used stack to store and retrieve the values. The complete code is given below in the further explanation section.
Further explanation:
Code:
The C++ code to print the last name as smith, first and last name as bill jones is as below:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//Define class
class BaseClass {
public:
void SetLastName(string givenName) {
lastName =givenName;
}
// Define the print function to print the first name and last name
protected:
string lastName;
};
class DerivedClass : public BaseClass {
public:
void SetFirstName(string givenName) {
firstName = givenName;
}
void PrintItem() {
cout << " first and last name : ";
cout << firstName << " " << lastName << endl;
};
private:
string firstName;
};
int main() {
BaseClass* BaseClassPtr = 0;
DerivedClass* DerivedClassPtr = 0;
vector<BaseClass*> itemList;
int i = 0;
BaseClassPtr = new BaseClass();
BaseClassPtr->SetLastName("Smith");
DerivedClassPtr = new DerivedClass();
DerivedClassPtr->SetLastName("Jones");
DerivedClassPtr->SetFirstName("Bill");
itemList.push_back(BaseClassPtr);
itemList.push_back(DerivedClassPtr);
for (i = 0; i < itemList.size(); ++i) {
itemList.at(i)->PrintItem();
}
return 0;
}
Output:
last name: smith
first and last name: bill jones
Learn more:
1. A company that allows you to license software monthly to use online is an example of ? brainly.com/question/10410011
2. How does coding work on computers? brainly.com/question/2257971
Answer details:
Grade: College Engineering
Subject: Computer Science
Chapter: C++ Programming
Keyword:
C++, input, output, programming, statements, loops, if, else, statements, firstname, lastname, base class, derive class, vector, print