Syntax error: 'constant' and Missing type specifier - int assumed. Note: C++ does not support default-int

Viewed 128

I am trying to create simple structure.

template <typename T>
struct Element
{
    T eValue;   // Element Value
    Element <T>* next_element;
};


template <typename T, int size>
struct dynamic_array
{
    Element <T> first_element;
    Element <T>* last_element = &first_element;

    add(2);

    void add(int count)
    {
        for (int i = 0; i < count; i++) {
            last_element -> next_element = new Element <T>;
            last_element = last_element -> next_element;
        }
    }
};

And as you can see, I'm trying to use add() function inside the structure, but I get these errors:

error C2059: syntax error: 'constant'

message : see reference to class template instantiation 'dynamic_array<T,size>' being compiled

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

warning C4183: 'add': missing return type; assumed to be a member function returning 'int'

But when I'm trying to use this function from main() function, code is being compiled successfully

int main()
{
    dynamic_array <int, 5> myArray;
    myArray.add(5);
}

I have no idea why I'm getting these errors. I can guess that it is something connected to template, because I started to use them recently

1 Answers

As pointed out by interjay you need to add the code inside the constructor to have it executed when you create the object. But you should understand the basic fact that template or not, you are defining a struct , compiler will convert it into respective structure when its used ( think of a vector) .Now when you create an object of the template struct , the memory is allocated for the object , prior to that there is no execution of any code. So if you want any code to be executed as soon as the object is created you put the code in consttuctor, if you want the code to execute at specific times like the add(int count) here, you put them inside a member function and call them when needed.

Related