1

I need to create an array of class template in C++ but compiler doesn't allow it. Example :

class CRefBase {
public:
    virtual ~CRefBase() = 0;
};

template<class T>
class CRef : public CRefBase {
private:
    T *Obj;
public:
    CRef(T *Obj){ this->Obj=Obj; }
}

in main function

CRefBase *refs;
refs=new CRefBase[200]; // Error in this line : cannot allocate an object of abstract type ‘CRefBase’

I see this topic but this isn't my answer.

Thanks

1

3 Answers 3

1

Even if you were to try to instantiate a derived class, it's a terrible idea, as arrays cannot be indexed in this way- when you index a pointer to CRefBase with any index other than 0, they must only ever be CRefBase, and cannot be any derived class.

Furthermore, there is a massive bunch of exception unsafety and memory leakage in the use of new[], which is banned from all reasonable codebases. It would be safe to use something like std::vector<std::unique_ptr<CRefBase>>, and then you might actually create a program that works, if you create an object of a derived class type.

Sign up to request clarification or add additional context in comments.

Comments

1

CRef is a class template, CRefBase is a (non-instantiable) abstract base class.

You're not doing what the title says:

How to create an array of templated class?

Oh, and you'll need an array of poitnters for polymorphism (and a virtual base class destructor):

CRefBase **refs = new CRefBase*[200];

for(size_t i = 0; i < 200; ++i)
    refs[i] = new CRef<whatever>(pointer_to_whatever_instance);

That's it. Have a nice time managing its dynamically allocated memory.

Comments

-1

the following code means a pure virtual function so that "CRefBase" is an abstract base class, which means that it can not be instantiated!

virtual ~CRefBase()=0;

As your question, the template supp.orts array. you can first fix your compilation problem then test it again

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.