0

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.

4
  • 3
    A smart pointer is used just like a regular pointer. Commented Oct 11, 2019 at 21:14
  • 4
    Put some code you're having trouble with into a minimal reproducible example, along with any compile errors you're getting. Commented Oct 11, 2019 at 21:15
  • The same BankAccount object? I can't figure out from this description if shared_ptr even makes sense. Otherwise, the comment about smart pointers being used the same holds.The real issue likely lies elsewhere. Commented Oct 11, 2019 at 21:34
  • 1
    Arrow notation should have done the job. Try it once more and if the problem's still there edit your question to describe that specific attempt. Commented Oct 11, 2019 at 21:44

1 Answer 1

2

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(); //... } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.