Mar 12, 2019 at 6:44pm Mar 12, 2019 at 6:44pm UTC
Hi,
I'm a student, and my c++ class has an online homework called zybooks and it's a mixture of participation and some challenges. We've begun classes, and it's 98% a self learning course, and I'm having trouble understanding what's going on in the code.
It's a snippet of code pre-coded by zybooks and I have to add in a piece of code to make it work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class BaseItem {
public :
void SetLastName(string providedName) {
lastName = providedName;
};
// i can only edit from here...
// FIXME: Define PrintItem() member function .... // this is my snippet.
void PrintItem(){
cout << "Last name: " << " " << lastName << endl;
}
// to here. I can't touch any of the rest of the code.
protected :
string lastName;
};
class DerivedItem : public BaseItem {
public :
void SetFirstName(string providedName) {
firstName = providedName;
};
void PrintItem() {
cout << "First and last name: " ;
cout << firstName << " " << lastName << endl;
};
private :
string firstName;
};
int main() {
BaseItem* baseItemPtr = nullptr ;
DerivedItem* derivedItemPtr = nullptr ;
vector<BaseItem*> itemList;
unsigned int i;
baseItemPtr = new BaseItem();
baseItemPtr->SetLastName("Smith" );
derivedItemPtr = new DerivedItem();
derivedItemPtr->SetLastName("Jones" );
derivedItemPtr->SetFirstName("Bill" );
itemList.push_back(baseItemPtr);
itemList.push_back(derivedItemPtr);
for (i = 0; i < itemList.size(); ++i) {
itemList.at(i)->PrintItem();
}
return 0;
}
My code inserts this into console stream:
Last name: Smith
Last name: Jones
It needs to insert this:
Last name: Smith
First and last name: Bill Jones
I know there's something to do with there being two void print functions being called, and I'm sure the problem lies therein, but I am so lost on classes right now.
**edit** it shouldn't be a void should it?
Last edited on Mar 12, 2019 at 6:52pm Mar 12, 2019 at 6:52pm UTC
Mar 12, 2019 at 7:25pm Mar 12, 2019 at 7:25pm UTC
It certainly passed all tests, so thank you for that.
A couple questions so I understand though:
Is virtual something that should be used for classes in general?
So, could I use lastName in any function because it's protected or because it's just part of a class?
Mar 12, 2019 at 8:32pm Mar 12, 2019 at 8:32pm UTC
Is virtual something that should be used for classes in general?
virtual
is used on functions in base classes where you want to overload the same function in the derived class.
could I use lastName in any function because it's protected
You can use lastname is any class derived from BaseItem.
Last edited on Mar 12, 2019 at 8:33pm Mar 12, 2019 at 8:33pm UTC