View Single Post
  #1 (permalink)  
Old January 1st, 2006, 12:29 AM
Jonax Jonax is offline
Friend of Wrox
 
Join Date: Jun 2003
Posts: 184
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Jonax
Default Unary operator overload and inheritance

Hi guys, and a happy new year...

I'm having some trouble inheriting overloaded operators - I've put together this little piece of code to illustrate my grievance...

It all works fine when I overload the prefix-operator - but if I overload the postfix-operator in a derived class, I get into all kinds of trouble - please give me some pointers!

Code:
/* 
** Overloading and inheritance
** tested using overloads of unary operators
** 051231 Jonax
*/

#include <iostream.h>
#include <conio.h>

class cApple
{
protected:
    int iWormCount;
    float fTotalLengthOfWorms;
public:
    cApple()
    {
        iWormCount = 0;
        fTotalLengthOfWorms = 0;
    }

    cApple(int iWC, float fTLoW)
    {
        iWormCount = iWC;
        fTotalLengthOfWorms = fTLoW;
    }

    cApple operator ++ () 
    {
        return cApple(++iWormCount, ++fTotalLengthOfWorms);
    }

    void put()
    {
        cout << "Number of worms: " << iWormCount << endl;
        cout << "Total length of worms: " << fTotalLengthOfWorms << endl;
    }
};

class cBigApple:public cApple
{
private:
    float fWeightInKilos;
public:
    cBigApple() : cApple()
    {
        fWeightInKilos = 0;
    }

    cBigApple(int iWC, float fTLoW, float fWiK) : cApple(iWC, fTLoW)
    {
        fWeightInKilos = fWiK;
    }

    cBigApple operator -- () 
    {
        return cBigApple(--iWormCount, --fTotalLengthOfWorms, 0.0);
    }
};

class cBigRedApple:public cBigApple
{
private:
public:
    cBigRedApple() : cBigApple()
    {
    }

    cBigRedApple(int iWC, float fTLoW, float fWiK) : cBigApple(iWC, fTLoW, fWiK)
    {
    }

    cBigRedApple operator -- (int)
    {
        return cBigRedApple(iWormCount--, fTotalLengthOfWorms--, 0.0);
    }
};

int main(){
    cApple oMyApple;
    ++oMyApple;
    cout << "oMyApple:" << endl;
    oMyApple.put();

    cBigApple oMyBigApple;
    ++oMyBigApple;
    ++oMyBigApple;
    ++oMyBigApple;
    cout << "\noMyBigApple:" << endl;
    oMyBigApple.put();

    cBigRedApple oMyBigRedApple;
    ++oMyBigRedApple;
    ++oMyBigRedApple;
    ++oMyBigRedApple;
    ++oMyBigRedApple;
    --oMyBigRedApple;
    oMyBigRedApple--;
    cout << "\noMyBigRedApple:" << endl;
    oMyBigRedApple.put();

    getch();
    return 0;
}



Reply With Quote