0

I am getting error C2512 when I am calling the constructor of a class from another class's constructor. I am using template instances at the bottom of the file, so that I wouldn't have to implement the member functions in the header. Normally, this is caused by not having a default constructor, but I do.

vec.h

template <class TYPE> class vec {
    struct vecimp;
    vecimp *imp;
public:
    vec() { }
    vec(const TYPE *, size_t);
    ~vec();
};

vec.cpp

#include "vec.h"
template <class TYPE> struct vec<TYPE>::vecimp {
    TYPE *arr;
    size_t n;
    vecimp(const TYPE *arr, size_t n)
    {
        this->arr = (TYPE *) malloc(n * sizeof(TYPE));
        this->n = n;
    }
    ~vecimp()
    {
        free(this->arr);
        this->arr = NULL;
    }
};

template <class TYPE> vec<TYPE>::vec(const TYPE *arr, size_t n)
{
    this->imp = 
        new vecimp
        <TYPE>             // C2512 occurs here
        (arr, n);
}

// member function implementations, dtor, etc

template class vec<int>;

Here is the error message text

'vec::vecimp': no appropriate default constructor available

So I tried to add a default constructor to my vecimp class, but then it gave me the compiler error C2275, at the same place as now.

Community
  • 1
  • 1
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • 1
    http://stackoverflow.com/a/495056/2469027 This answer says you can put the declarations you need at the bottom of your .cpp file. @LogicStuff – lost_in_the_source Feb 21 '16 at 15:35

1 Answers1

1

The problem is that you try to create an instance of vecimp<TYPE>, but vecimp is not a templated structure.

So simple

this->imp = 
    new vecimp
    (arr, n);

will work just fine.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • This works, but how is `vecimp` not templated? I write `template `, and use `TYPE *arr` inside of `vecimp`. – lost_in_the_source Feb 21 '16 at 15:43
  • 1
    @stackptr The `vec` class is a templated class, but not `vecimpl` itself. If you want to fully qualify it then it would be `vec::vecimpl`, the template argument belongs to the `vec` class. Since `vecimpl` is inside the `vec` template, it can of course use `TYPE`. – Some programmer dude Feb 21 '16 at 15:43