0

I have one (abstract) parent class and some more children classes.

template <typename T>
class parent {

public:
    T data; 
    virtual T method(T t) = 0; 
};


template <typename T>
class child : public parent<T> {
public:

    child(){
        cout << "test" << endl; 
    }

    T method(T t){
       cout << t << endl; 
    }
}; 

template <typename T>
class child2 : public parent<T> {
public:

    child2(){
        cout << "test2" << endl; 
    }

    T method(T t){
       cout << "other" << endl; 
    }
}; 

Then I have a main Class that has a pointer to an array of parent pointers

template <typename T>
class mainClass{
    public:
        mainClass(){
            ptr = new child<T>[10]; 
            for (int i = 0; i < 10; i++)
            {
                ptr[i] = NULL; 
            }
            
        }
        parent<T>** ptr; 
};

Now, I dynamically want to assign this array to a certain child class.

  ptr = new child<T>[10]; 

But somehow this does not work.

 error: incompatible pointer types assigning to 'parent<int> **' from 'child<int> *'

What should I do ? If you need any clarifications let me know Thanks in advance.

Jonny

  • 1
    Can't be done for many reasons. You can assign `child*` to `parent*`, but that does not mean that you can assign `child**` to `parent**`. Additionally you have your indirection wrong in your example, you have X** (double pointer) on the left hand side, and Y* (single pointer) on the right hand side. – john Nov 22 '22 at 08:17

1 Answers1

2

First of all don't use new and delete, this is "old" C++ and prone to many problems. Instead use specialized containers like std::vector<parent<T> *> and smart pointers. And then you can assign vector elements with pointers to both child and child2.

E.g. something like this:

template <typename T>
class mainClass{
    public:
        mainClass(){
            children.resize(10, nullptr);
            // If pointers owned by mainClass use std::unique_ptr to manage them
            children[0] = std::make_unique<child>();
        }
        // Use this if pointers is owned by someone else
        std::vector<parent<T>*> children;
        // Use this if pointers is owned by mainClass
        std::vector<std::unique_ptr<parent<T>>> children;
};
sklott
  • 2,634
  • 6
  • 17
  • Sidenote, you should prefer sizing the vector either within member initializer list, or by providing a default value. Also the `nullptr` within `vector::resize` is not needed as new datas are value initialized. – Ranoiaetep Nov 22 '22 at 09:49