2

I've been writing some code for a project that includes OpenGL, and I've discovered weird behavior with my vec4 struct, of which I could not find an explanation.

Here's the relevant snippet of my code:

#include <iostream>
using namespace std;

template <class T>
struct vec4 {
    T data[4];
    vec4(T v1 = (T) 0, T v2 = (T) 0, T v3 = (T) 0, T v4 = (T) 1) {
        data[0] = v1;
        data[1] = v2;
        data[2] = v3;
        data[3] = v4;

    }
    void print() {
        cout << "[ " << data[0] << ", " << data[1] << ", " << data[2] << ", " << data[3] << " ]" << endl;

    }
};
int main() {
    vec4<int> test1;     //Instantiating like this is fine
    test1.print();

    vec4<int> test2();   //Instantiating like this leads to errors
    test2.print();

    vec4<int> test3(0);  //Instantiating like this is also fine
    test3.print();

    // ...

    return 0;

}

As you can see, the only difference is using parentheses or not. When I use the parentheses, I get various errors such as:

main.cpp:222:11: error: request for member 'print' in 'test2', which is of non-class type 'vec4<int>()'

main.cpp:226:18: error: no match for 'operator*' (operand types are 'matrix<int>' and 'vec4<int>()')

I get none of these errors if I exclude the parentheses. (I should note that there is an operator overload function defined, but excluded from my snippet. It works with matrix<int> and vec4<int>.)

Does anyone have an explanation to this behavior? Are there any situations where such behavior could lead to problems?

Thank you!

jxh
  • 69,070
  • 8
  • 110
  • 193
Drayux
  • 73
  • 6
  • 2
    Most vexing parse. – jxh Sep 30 '19 at 04:46
  • 2
    It can be a good idea to run code through Clang if you can't figure out something GCC gives you. Clang gives a [really nice warning](https://gcc.godbolt.org/z/H_Ydxg) here. – chris Sep 30 '19 at 04:48
  • You're right, it looks like it is interpreted as a function declaration. Thanks chris! – Drayux Sep 30 '19 at 04:54
  • 1
    I want to note that this was a well asked question, it just happens to have been asked before. +1 from me. – jxh Sep 30 '19 at 18:29
  • Thank you, jxh! Sometimes it would seem no matter how much you search, you just can't search the right question sometimes. Despite it being an accidental duplicate, I still learned what I hoped to, so I appreciate the help! – Drayux Oct 01 '19 at 03:26

0 Answers0