user2967016
user2967016

Reputation: 133

Redundancy in post-increment overloading?

// The following operator++() represents overloading of pre-increment 
MyIncrDecrClass& operator++()  
{ 
    ++this->m_nCounter; 
    return *this; 
} 

// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass& operator++(int)  
{ 
    this->m_nCounter++; 
    return *this; 
} 

So this is how a post and pre increment operator are implemented, but in my case I can't really implement it like that, so this is what I did:

VLongInt& VLongInt::operator++()
{
    ... //BUILD TEMP vector
    this->vec = temp;
    return *this;
}

VLongInt& VLongInt::operator++(int)
{
    this->vec = this.vec; //seems unnecessary
    ... //BUILD TEMP vector
    this->vec = temp
    return *this;
}

Is there anything wrong? It seems that both should be implemented the same way. Only the header file should differ, right?

Upvotes: 0

Views: 127

Answers (2)

Shoe
Shoe

Reputation: 76280

Is there anything wrong?

Yes, with your code you are violating the ODR (one definition rule). Which is defined in § 3.2/1 as:

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

You should define these two functions instead:

VLongInt& VLongInt::operator++();
const VLongInt VLongInt::operator++(int);

Specifically, please, note that the post increment operator should return either const T or T (with T being your class type).

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

Your example of overloading of the postincrement operator is wrong.

Intsead of

// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass& operator++(int)  
{ 
    this->m_nCounter++; 
    return *this; 
} 

there should be

// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass operator ++( int )  
{
    MyIncrDecrClass tmp( *this );

    ++this->m_nCounter; 

    return tmp; 
}

ALso your problem is totally unclear. You defined in fact the same operator twice

VLongInt& VLongInt::operator++()
{
    //...
    return *this;
}

VLongInt& VLongInt::operator++()
{
    //...
    return *this;
}

I do not see a difference. Moreover you did not show your class definition and as the result nothing can be said about your problem. It is unknown.

At least as you said yourself your postincrement operator should be declared with a dummy parameter of type int. And it has to return a temporary object.

VLongInt  VLongInt::operator ++( int )

or

const VLongInt  VLongInt::operator ++( int )

Upvotes: 2

Related Questions