call copy constructor from assignment operator function

c++, visual-studio

Solution

The offending line isn't what you think it is. It actually declares a variable `other` of type `FeatureValue`. This is because constructors to not have names and cannot be called directly.

You can safely invoke the copy assignment operator from the constructor as long as the operator is not declared virtual.

FeatureValue::FeatureValue(const FeatureValue& other)
    : m_value(nullptr), m_size(0)
{
    *this = other;
}

// assignment operator function
FeatureValue& FeatureValue::operator=(const FeatureValue& other)
{
    if(this != &other)
    {
        // copy data first. Use std::unique_ptr if possible
        // avoids destroying our data if an exception occurs
        uint8_t* value = new uint8_t[other.m_size];
        int size = other.m_size;  

        for (int i = 0; i < other.m_size; i++)
        {
            value[i] = other.m_value[i];
        }

        // Assign values
        delete[] m_value;
        m_value = value;
        m_size = size;
    }
    return *this;
}

This will works just dandy or you can use the typical guidelines for the copy & swap idiom suggested in Vaughn Cato's answer

Problem

I have a class with a point to dynamically allocated array, so I created copy constructor and assignment operator function. Since copy constructor and assignment operator function do the same work, I call copy constructor from the assignment operator function but get `"error C2082: redefinition of formal parameter"`. I am using Visual Studio 2012. ``` // default constructor FeatureValue::FeatureValue() { m_value = NULL; } // copy constructor FeatureValue::FeatureValue(const FeatureValue& other) { m_size = other.m_size; delete[] m_value; m_value = new uint8_t[m_size]; for (int i = 0; i < m_size; i++) { m_value[i] = other.m_value[i]; } } // assignment operator function FeatureValue& FeatureValue::operator=(const FeatureValue& other) { FeatureValue(other); // error C2082: redefinition of formal parameter return *this; } ```

Original source

Related problems