1

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
}
  • Please show how you use this method. It going to make a new `T`s so it all depends on how you call it. – Richard Critten Jan 11 '22 at 19:18
  • 2
    You're looking for what's sometimes called [a virtual constructor](https://isocpp.org/wiki/faq/virtual-functions#virtual-ctors) or a clone. – user4581301 Jan 11 '22 at 19:19
  • 1
    I'm making a few assumptions here, but it looks like OP is using runtime polymorphism, creating objects of type Base and Derived and using pairs of type Pair; that would explain `new T` would always create objects of type `Base*`. – rturrado Jan 11 '22 at 20:18

1 Answers1

1

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;
}
Amir Kirsh
  • 12,564
  • 41
  • 74
  • Yes, it has, but I wanted to pass only pointer of main class, and I wondered can I somehow know is pointing on object of main or derived class, and depending on that to make an object. I wanted to use polymorphism. – Nikola Nikolic Jan 12 '22 at 18:02