[Discuss] OT - C++ operator overloading question.

John Vetterli jvetterli at linux.ca
Wed Aug 30 07:23:12 PDT 2006


On Wed, 30 Aug 2006, David Wu wrote:
> ...
> class NumData
> {
>   public:
>       NumData(int a, long long b);
>       ~NumData();
>       NumData& operator++();
>       NumData& operator--();
>       void displayInfo();
>   private:
>       int m_nValue;
>       long long m_llnValue;
> };
> ...
> int main()
> {
>   NumData* myNumData = new NumData(1, 10);
>   myNumData->displayInfo();
>   ++myNumData;
>   myNumData->displayInfo();
>   if(myNumData != NULL)
>   {
>       delete myNumData;
>       myNumData = NULL;
>   }
>   return 0;
> }
> ===============================================

Oops, you're incrementing the pointer, not the object it's pointing to. 
Try ++*myNumData instead of ++myNumData.

Also, IIRC, operator++() and operator--() define postincrement and 
postdecrement operators; use operator++(int) and operator--(int) to define 
preincrement and predecrement (the int is just a dummy value).

HTH
JV


More information about the Discuss mailing list