1

I have a generic class defined down below, with member parameter an array, i.e. T grades[5];

when I declare object of this class, using

StudentRecord<int> srInt();

and then call a member function of the class, using

srInt.setGrades(arrayInt);

I get an error,

error: request for member ‘setGrades’ in ‘srInt’, which is of non-class type ‘StudentRecord<int>()’
     srInt.setGrades(arrayInt);

but when i declare class using(below), and try to call same function, it works

StudentRecord<int> srInt;
//header file for main.cpp

#include<iostream>

using namespace std;
const int SIZE=5;

template <class T>
class StudentRecord
{
    private:
        const int size = SIZE;
        T grades[5];
    public:
        void setGrades(T* input);
};

template<class T>
void StudentRecord<T>::setGrades(T* input)
{
    for(int i=0; i<SIZE;++i)
    {
        grades[i] = input[i];
    }
}

My question is there any difference between declaring class,

StudentRecord<int> srInt();

v/s

StudentRecord<int> srInt;
Vishal
  • 13
  • 2

1 Answers1

2

This is not about templates ("generic class").


Just like int f(); is a function declaration, StudentRecord<int> srInt();s is a function declaration. Yes, even when you write it in a function.

Remove the () and you get an object declaration instead.

That's it!


Some people call this the "Most vexing parse", though it is not actually an example of that. It does involve some of the same grammar/language rules to a degree.

When you wrote StudentRecord<int> srInt(-1);, that is a valid object declaration, because there is no way it can be a function declaration (-1 is not an argument declaration).

If -1 were swapped for a more complex expression, it's possible to get surprised by the fact that it gets interpreted as a valid argument declaration. Like int f(int());. That's the most vexing parse.


There's no magic or strangeness here; you just have to use the right symbols for what you want.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35