0

Alright so what I am trying to do is basically this.

I have an Account class, then I have a CheckingAccount and SavingsAccount class that inherit from the Account class.

In my program I have an array called accounts. It is going to hold objects of both types of accounts.

Account** accounts;
accounts = new Account*[numAccounts];


accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
CheckingAccount tempAccount(tempBalance, tempAccountNum, tempTransFee);
accounts[i] = tempAccount;

I get an error when trying to assign tempAccount to the accounts array.

No suitable conversion function from "CheckingAccount" to "Account" exists.

How do I make the accounts array hold both kinds of objects?

2 Answers 2

2

Each element in accounts is an Account*. That is, a "pointer to Account". You're trying to assign an Account directly. Instead, you should be taking the address of that account:

accounts[i] = &tempAccount;

Remember that this pointer will be pointing at an invalid object once tempAccount has gone out of scope.

Consider avoiding arrays and pointers. Unless you have a good reason not to, I would use a std::vector of Accounts (not Account*s):

std::vector<Account> accounts;

accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
accounts.emplace_back(tempBalance, tempAccountNum, tempTransFee);
Sign up to request clarification or add additional context in comments.

2 Comments

ok, so now I am at the problem you said I would end up at. Where as soon as I close my accounts file. The accounts array becomes NULL. How would I be able to keep these objects in the array after closing the file?
@user2234688 You should post a new question. I'm not avoiding it- that's just generally how things are done here!
0

I believe that you need to assign the address of tempAccount into the accounts array.

accounts[i] = &tempAccount;

Because, when dealing with polymorphism in C++, you use the address of the object rather than the object itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.