Ryan J. Shrott
Ryan J. Shrott

Reputation: 602

Generic Inheritance and Copy Constructor

I created a generic Array class and then used generic inheritance to create a NumericArray class. When I use the default copy constructor (in NumericArray) I get the correct results from my member functions; however, when I implement my own copy constructor in the NumericArray class, I get incorrect results. In particular, free functions in NumericArray.h, that rely on the NumericArray copy constructor, produce strange values, such as -8386226262.

The copy constructor for the generic Array is:

template <typename Type>
Array<Type>::Array(const Array<Type>& data) // copy constructor 
{
    m_size = data.m_size; // set m_size to the size of the data which should be copied
    m_data = new Type[m_size]; // allocate memory on the heap for m_data to be copied from the new data array 
    for (int i = 0; i < m_size; ++i)
    {
        m_data[i] = data.m_data[i]; // copy each element one at a time 
    }
    cout << "Copy called" << endl;
}

and the copy constructor for the generically inherited NumericArray is:

template <typename Type> // copy constructor 
NumericArray<Type>::NumericArray(const NumericArray<Type> &source)
{
    Array<Type>::Array(source); // calls the copy constructor of a generic Array (since a numeric array performs the same copy as a generic array here)
    cout << "Numeric copy called!" << endl;
}

Are there any problems you notice with these implementations?

For anyone who would like full access to the program, I put it on dropbox, here: https://www.dropbox.com/sh/86c5o702vkjyrwx/AAB-Pnpl_jPR_GT4qiPYb8LTa?dl=0

Upvotes: 1

Views: 417

Answers (1)

Jarod42
Jarod42

Reputation: 217663

template <typename Type> // copy constructor 
NumericArray<Type>::NumericArray(const NumericArray<Type> &source)
{
    Array<Type>::Array(source); // calls the copy constructor of a generic Array (since a numeric array performs the same copy as a generic array here)
    cout << "Numeric copy called!" << endl;
}

should be

template <typename Type> // copy constructor 
NumericArray<Type>::NumericArray(const NumericArray<Type> &source) :
    Array<Type>::Array(source) // calls the copy constructor of a generic Array (since a numeric array performs the same copy as a generic array here)
{
    cout << "Numeric copy called!" << endl;
}

as the following is local to your function

Array<Type>::Array(source);

Upvotes: 1

Related Questions