Dave ddd
Dave ddd

Reputation: 117

C++ : why convert to void* before doing a test

Does anyone know why the two pointers this and &op2 are first converted to void* before comparing them? (this example is taken from C++ templates: The complete Guide by David Vandevoorde and Nicolai M. Josuttis)

template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){
    if ((void*)this==(void*)&op2){
        return *this;
    }
    // ....
}

Upvotes: 4

Views: 182

Answers (1)

R Sahu
R Sahu

Reputation: 206567

As mentioned by @KerrekSB in a comment, this is poor coding style.

What the author is trying to do is avoid compile time warning for comparing pointers of different types, such as a pointer of type Stack<int>* and a pointer of type Stack<double>*.

It could be easily avoided by using overloads.

// Assign an object of the same type.
template<typename T>
Stack<T>& operator=(const Stack<T> & op2){
    if (this == &op2){
        return *this;
    }
    // ....
}

// Assign an object of a different type.
template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){

    // For objects of different types, this check is not necessary
    // at all. It will always be false.
    // if ((void*)this==(void*)&op2){
    //     return *this;
    /// }

    // ....
}

Upvotes: 3

Related Questions