So for a class assignment we have started using shared_pointers within vectors like so: vector<shared_ptr<BankAccount>> @accountsVector where my professor explains that the vector contains a list of shared pointers and each pointer points to a class BankAccount object. My question is, how do I access those objects in the BankAccount class? I have tried using an Index in a for loop with arrow notation and dot notation. If there's similar question point me in the right direction please.
1 Answer
For example, if BankAccount has a member getBalance(), then you can do things like this:
vector<std::shared_ptr<BankAccount>> accountsVector; ... accountsVector.push_back(std::make_shared<BankAccount>()); accountsVector.push_back(std::make_shared<BankAccount>()); ... double balance; balance = accountsVector[0]->getBalance(); balance = accountsVector[1]->getBalance(); // etc... vector<std::shared_ptr<BankAccount>> accountsVector; ... accountsVector.push_back(std::make_shared<BankAccount>()); accountsVector.push_back(std::make_shared<BankAccount>()); ... for(auto &account : accountsVector) { double balance = account->getBalance(); //... }
shared_ptreven makes sense. Otherwise, the comment about smart pointers being used the same holds.The real issue likely lies elsewhere.