My program will not compile with the error “Overloaded functions have similar conversion”. What does this mean and how do I fix it?
For what it’s worth, I’m following a tutorial and typed in exactly what it said. This same program works for them but not for me.
The error is at this line: if (intPtr == operand2.intPtr)
.
"could be bool Dynamic::operator==(const DynamicInt &)" while trying to match the argument list '(DynamicInt, DynamicInt)'
The program:
#include <vector>
#include <array>
#include <memory>
#include <utility>
#include <functional>
#include <cstddef>
#include <type_traits>
#include<iostream>
class DynamicInt
{
public:
DynamicInt()
: intPtr{ new int {0} }
{
}
DynamicInt(int value)
: intPtr{ new int { value } }
{
std::cout << "one parameter ctor" << std::endl;
}
~DynamicInt()
{
delete intPtr;
std::cout << "Destructed." << std::endl;
}
void SetValue(int newValue)
{
*intPtr = newValue;
}
int GetValue() const
{
return *intPtr;
}
// COPY CTOR
DynamicInt(const DynamicInt& other)
: intPtr{ new int { 5 } }
{
std::cout << "copy CTORn";
}
// MOVE CTOR -->>>> NOT GETTING HIT !!!!! :(
DynamicInt(DynamicInt&& other) noexcept
: intPtr{ other.intPtr }
{
std::cout << "move con called. n";
other.intPtr = nullptr;
}
// COPY ASSIGNMENT OPERATOR -> Used when "ASSIGNING" one object to another
DynamicInt& operator=(const DynamicInt& operand2)
{
std::cout << "Copy Assignment CTOR called." << std::endl;
// dont do anything if you both operands
// refer to the same object
if (intPtr == operand2.intPtr)
{
return *this;
}
// deep copy -> will allocate a NEW MEMORY BLOCK and initialize it with the value of RHS' integer
*intPtr = operand2.GetValue();
std::cout << "this: " << this << std::endl; // this is THE ADDRESS OF THE CURRENT OBJECT
return *this; // *this is a pointer that points to THE CURRENT OBJECT we are working on.
}
// OPERATOR OVERLOADING -> Used when "COMPARING" one object with another. Defines what happens when operand1 == operand2
bool operator==(const DynamicInt& operand2)
{
std::cout << "OPERATOR OVERLOAD called." << std::endl;
// here, we mean both are "equals" when both objects' INT values are the same
if (intPtr == operand2.intPtr)
{
return true;
}
if (GetValue() == operand2.GetValue())
{
return true;
}
return false;
}
int main()
{
DynamicInt intCOne{ 20 };
DynamicInt intCTwo{ 21 };
intCOne = intCTwo; // we implemented an ASSIGNMENT OPERATOR CTOR which uses DEEP COPY, so now, there is no error!
// OPERATOR OVERLOADING
if (intCOne == intCTwo)
{
std::cout << "Values are the same " << std::endl;
}
}
New contributor
Xmaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.