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

Community
  • 1
  • 1
MohsenTi
  • 361
  • 1
  • 2
  • 17
  • It seems you want to handle array polymorphically, don't do that. [Why is it undefined behavior to `delete[]` an array of derived objects via a base pointer?](http://stackoverflow.com/q/6171814/3309790) – songyuanyao Dec 19 '15 at 12:15

3 Answers3

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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
-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