b4kancs
b4kancs

Reputation: 105

C++ template class with argument copy constructor

I have a c++ generic class that looks like this:

template <class T, int N> class TwoDimArray{
    private:
        T tda_[N][N];
        int n_;
    public:
        TwoDimArray(T tda[][N]){
           ..
        }
        ~TwoDimArray(){
           ..
        }
        ..
}

How would I write a copy constructor that I will be able to call somehow like this:

int a1[][2] = { 1, 2, 3, 4 };
TwoDimArray <int, 2> tdm1(a1);
TwoDimArray tdm1Copy (tmd1); // or whatever the correct form is

I hope I was clear.

Upvotes: 2

Views: 681

Answers (1)

vsoftco
vsoftco

Reputation: 56567

You have lots of typos in your code, but declaring a copy constructor is simple:

TwoDimArray(const TwoDimArray& rhs){/*implement it here*/}

The copy constructor is part of a template class, so you must specify the template type when copying

TwoDimArray<int, 2> tdm1Copy (tdm1); // specify <int,2> as the type

or use auto

auto tdm1Copy(tdm2);

Full working example below:

#include <iostream>

template <class T, int N> class TwoDimArray {
private:
    T tda_[N][N];
    int n_;
public:
    TwoDimArray(T tda[][N]) {
        // implement
    }
    ~TwoDimArray() {
        // implement
    }
    TwoDimArray(const TwoDimArray& rhs) // don't really need this
    {
        // implement
    }
};

int main()
{
    int a1[][2] = { 1, 2, 3, 4 };
    TwoDimArray <int, 2> tdm1(a1);
    TwoDimArray<int, 2> tdm1Copy (tdm1); // specify <int,2> as the type
}

Unless you are doing this for a homework or learning purposes, just use std::vector<std::vector<T>> to "simulate" a 2-D array.


Additional remark: Since your class contains an array (and not a pointer, they are not the same), you don't need a copy constructor. The default copy constructor does it for you, i.e. copies the array element by element. So, just get rid of the copy constructor altogether and let the compiler generate a default one.

Upvotes: 1

Related Questions