Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing printable representation of an object similar to __repr__ in Python

Tags:

c++

I'm fairly new to C++ mostly have used Python in the past and am looking for a way to easily construct a printable representation of an object - similar in vein to Python's repr. Here are some snippets from my code (it's a bank of course).

    class Account   {
    private:
        int pin;
        string firstName;
        string lastName;
        char minit;
        int acc_num;
        float balance;
        float limit;
    public:
        float getBalance(void);
        string getName(void);
        void setPin(int);
        void makeDeposit(float);
        void makeWithdrawal(float);
        Account(float initialDeposit, string fname, string lname, char MI = ' ', float x = 0);
    };
Account::Account(float initialDeposit, string fname, string lname, char MI, float x)  {
    cout << "Your account is being created" << endl;
    firstName = fname;
    lastName = lname;
    minit = MI;
    balance = initialDeposit;
    limit = x;
    pin = rand()%8999+1000;
}

Account object constructed. I want to have a Bank object which is essentially an array of account objects.

    class BankSystem    {
    private:
        vector<Account> listOfAccounts;
        int Client_ID;
    public:
        BankSystem(int id);
        void addAccount(Account acc);
        Account getAccount(int j);
    };
BankSystem::BankSystem(int id)  {
    Client_ID = id;
    listOfAccounts.reserve(10);
}

I would like to give the Bank class showAccounts method function which displays to the user all the account objects that they have access to. I'd like to make this printable so I can display it in cout. In Python I'd simply just use the __repr__ to "stringify" the account objects e.g.

def __repr__(self):
    return 'Account(x=%s, y=%s)' % (self.x, self.y)

Wondering how I'd go about doing the same in C++. Thanks!

like image 709
quantik Avatar asked Jan 23 '26 05:01

quantik


1 Answers

The idiomatic way to go about this is to overload the operator<< function for output streams with your class, for example

#include <iostream>

using std::cout;
using std::endl;

class Something {
public:

    // make the output function a friend so it can access its private 
    // data members
    friend std::ostream& operator<<(std::ostream&, const Something&);

private:
    int a{1};
    int b{2};
};

std::ostream& operator<<(std::ostream& os, const Something& something) {
    os << "Something(a=" << something.a << ", b=" << something.b << ")";
    return os;
}

int main() {
    auto something = Something{};
    cout << something << endl;
}
like image 85
Curious Avatar answered Jan 24 '26 21:01

Curious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!