I am storing objects of base and derives classes (Account, StudentAccount, EmployeeAccount) in an STL list and process them with STL Iterator. The dynamic polymorphic behavior of objects is not happening. After reading few post at this forum, it "seems" to me (since i am not much able to understand deep tech reasons) polymorphic behavior in STL list is not possible. I wanted to know if polymorphic behavior is not possible, what’s the work around? If my perception is incorrect, please share a link or code sample. I am stuck in middle of a prototype. Below is the major code portion:
(using Visual Studio 2022 with ISO C++ 14, console application)
list<Account>* log = new list<Account>(); // in constructor
bool Bank::add(const Account& acc)
{
// do some checking here
this->log->push_back(Account(acc));
return true;
}
bool Bank::addAccount(...parameter here...)
{
return this->add(Account(...parameter here...));
}
bool Bank::addStudentAccount(...parameter here...)
{
return this->add(StudentAccount(...parameter here...));
}
2
Answers
This is called "slicing": if you put a derived class into that list, only the
Account
"sub-part" is actually stored there. Same if you copy aStudentAccount
to anAccount
— theStudent
-part simply gets "sliced off" because it has no place to go.The way around this is very simple: store pointers.
I think one of the comments above has answered your question to a degree. To repeat, polymorphism is only possible when using a pointer to the base class for method invocation – in this case a pointer of type "Account *"
On a side note – I strongly suggest playing with polymorphism to get used to the idea before you jump into combining it with Templates. It will make life much easier even if its only a prototype.
I wish you the best in your C++ journey!!