Reputation: 1597
I have a basic class called BankAccount
that looks like this:
class BankAccount {
private:
char* accountId;
int* ownerId;
double* accountBalance;
// some other methods here...
}
My question is about the creation of an object using the input operator. I observed that when I use it, 2 objects are in fact created, since the destructor is called twice in the end:
1. The implicit constructor is called
2. The values for initializing the object are provided from the stdin
3. The copy constructor is called
4. The destructor is called twice
5. The object is printed to the stdout
Can you explain me how does it actually work and if it can be avoided? I supposed the parameter bankAccount
is modified directly.
My functions are:
// 3. input operator
friend istream &operator>>(istream &in, BankAccount &bankAccount ) {
cout << "Enter the account ID:" << endl;
in.get(bankAccount.accountId, SIZE);
cout << "Enter the owner ID:" << endl;
in >> *bankAccount.ownerId;
cout << "Enter the account balance:" << endl;
in >> *bankAccount.accountBalance;
return in;
}
// 4. output operator
friend ostream &operator<<(ostream &out, BankAccount bankAccount ) {
out << endl;
out << "Account id: " << bankAccount.getAccountId();
out << endl;
out << "Owner id: " << bankAccount.getOwnerId();
out << endl;
out << "Account balance: " << bankAccount.getAccountBalance();
out << endl << endl;
return out;
}
and the invocation:
BankAccount bankAccount;
cout << "Enter the values to build a new object: " << endl;
cin >> bankAccount;
cout << bankAccount;
Upvotes: 1
Views: 1941
Reputation: 2874
As suspected you get the copy by passing the object to operator <<
call-by-value
BankAccount bankAccount; // Default constructor call
cout << "Enter the values to build a new object: " << endl;
cin >> bankAccount; // Read in values
cout << bankAccount; // Create a copy of bankAccount and pass it to operator <<
To avoid this change operator << to
friend ostream &operator<<(ostream &out, const BankAccount &bankAccount ) {
This is call-by-reference and will avoid the copying of the BankAccount object
Upvotes: 5