jeudi 25 janvier 2018

getting size of child object inside parent function

I want to know the size of the derived class object inside parent function. The parent function in my case is virtual and hence I cannot use sizeof(child class name) and I have to decide dynamically based on the object passed. Below is the code snippet. I used sizeof(*this) inside PrintBalance() of parent class and that will not work. I need something similar to that. I am explicitly calling parent class function from overridden child class.

class Account
{
protected:
    int var1;
    int var2;
    double m_balance;

    public:

    Account( double d )
    {

        m_balance = d;
    }

    virtual double GetBalance()
    {
        return m_balance;
    }
    virtual void PrintBalance()
    {
        cout<<"size in Parent= "<< sizeof(*this)<<endl;
    }
private:

};

class CurrentAccount : public Account
{
    int var3;
    int var4;
public:
    CurrentAccount(double d) : Account(d) {}

    void PrintBalance()
    {
        Account::PrintBalance();
        cout<<"size in Derived = "<< sizeof(*this)<<endl;
        cout << "Current account balance: " << GetBalance() << endl;
    }
};

int main()
{
    CurrentAccount cAcc(1000);
    CurrentAccount *pCurrent = &cAcc ;
    pCurrent->PrintBalance();
    pCurrent->GetBalance();
}

Aucun commentaire:

Enregistrer un commentaire