0

I have a program with some classes for OpenGL stuff e.g. Window, Program etc.

I want the instances of the Window and Program classes which I use in my main file to be global for the main file, I'd been doing this for a while with Window like this

//Outside main()
Window window
(
    "test",    //title
    1366,      //width
    768,       //height
);

Then I can use this instance in the rest of the main file e.g.

//Within main()

window.create();

window.refresh();

etc.

Now when I try to make a global instance of Program I do it like this:

//Just below Window, still outside main()
Program program();    //No arguments for the constructor for Program

Then when I try to use it in my main function like this:

program.addShader(GL_VERTEX_SHADER, "vertex_shader_source.glsl");

I get the error:

request for member 'addShader' in 'program', which is of non-class type 'Program()'

Having looked into this it looks like the compiler thinks that my initialisation of the instance before main() is a function instead so it thinks I'm trying to call methods on a function which obviously doesn't work.

I just can't work out how to make this work in the way that it does for Window, the key differences that I can tell which might mean Window works and Program doesn't are:

  • The constructor for Window has arguments and Program doesn't.
  • I have other instances of the Program class in main() other than this global one, of course they have different name but still it might cause some problem?
DomAyre
  • 828
  • 1
  • 11
  • 23

3 Answers3

2

You've discovered what's called the most vexing parse.

Indeed, when you do that:

Program program();

it is ambiguous, as you could be doing two things:

  • Creating a variable program which ctor takes no argument
  • Declaring a function called program which returns a Program and takes no argument

And the C++ standard imposes that a compiler choose the second possibility when it encounters this code.

To avoid this problem, just remove the parens

//Declares and defines a new program variable by invoking the default ctor
Program program;
JBL
  • 12,588
  • 4
  • 53
  • 84
0

Use

Program program;

instead of

Program program(); 

You do not need to use parens for constructor without parameters. Actually the second construct is interpreted as function declaration (function without parameters returning Program).

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

Don't write it like this:

Program program();

because the parser thinks you just declared a function called "program" with no arguments, which return Program instance.

This is the correct way to define an object using its default constructor:

Program program;