Nikola Nikolic
Nikola Nikolic

Reputation: 121

template copy of derived class

I'm making copy of template class that can contain pointer on object or pointer of derived class. I tried with allocation on heap but it continuously making object of main class, doesn't matter is it of derived or main class. How can I fix it. Code is huge, this is a part where I tried it:

template<typename T> 
inline void Pair<T>::copy(const Pair& p) {
    pointerAttribute1 = new T(*p.getFirst());//this is an object of main class in my main
    pointerAttribute2 = new T(*p.getSecond());//this is an object of derived class in my main
}

Upvotes: 1

Views: 82

Answers (1)

Amir Kirsh
Amir Kirsh

Reputation: 13752

It sounds like your pair has two types.

So why not represent that in the template? Something like:

template<typename T1, typename T2> 
inline void Pair<T1, T2>::copy(const Pair<T1, T2>& p) {
    if(this == &p) return;
    delete p1;
    delete p2;
    p1 = new T1(*p.p1);
    p2 = new T2(*p.p2);
}

But then, maybe instead of implementing copy you can go with assignment operator:

template<typename T1, typename T2> 
inline Pair<T1, T2>& Pair<T1, T2>::operator=(const Pair<T1, T2>& p) {
    if(this != &p) {
        delete p1;
        delete p2;
        p1 = new T1(*p.p1);
        p2 = new T2(*p.p2);
    }
    return *this;
}

Upvotes: 1

Related Questions