Home > Mobile >  How can I trigger copy constructor of a parent templated class inside the child class
How can I trigger copy constructor of a parent templated class inside the child class

Time:06-06

How can I call the copy constructor of the parent templated class inside the copy constructor of the child class?

// Type your code here, or load an example.
#include<vector>
#include <iostream>

template <typename T>
class Parent {
public:
    Parent() {};
    const std::vector<T>& getDims() const { return m_dims; };
    void setDims(const std::vector<T> dims) { m_dims = dims; };
    Parent(const Parent& p) { m_dims = p.getDims(); };
private:
    std::vector<T> m_dims;
};

template <typename T>
class Child : public Parent<T> {
public:
    Child() {};
    const std::vector<T>& getCenter() const { return m_center; };
    void setCenter(const std::vector<T> center) { m_center = center; };
    Child(const Child& c) {
        m_center = c.getCenter();
        // How can I trigger the copy constructor of the parent class
        // and copy m_dims instead of the following
        this->setDims(c.getDims());
    }
private:
    std::vector<T> m_center;
};

int main(){
    Child<int> child1;
    child1.setDims({3, 1, 1, 1}); // Parent function
    child1.setCenter({1, 2, 3, 4}); // Child function

    Child<int> child2 = child1;
    return 0;
}

CodePudding user response:

template <typename T>
class Child : public Parent<T> {
public:
    Child() {};
    Child(const Child& c): Parent<T>(c) {
        m_center = c.getCenter();
    }
private:
    std::vector<T> m_center;
};

Your base class is Parent<T> here.

  • Related