1

I want to hand over to a function a pointer to an object and then work with this in the function. However this somehow does not work. Please excuse if my nomenclature is not correct. I haven't worked with c++ for a while. Here is my code:

#include <iostream>
#include <array>
#include <fstream>

class Grid {
public:
  std::array<std::array<std::array<double,10>, 10>, 10> chi;
  Grid();
};

Grid::Grid()
{
  std::array<std::array<std::array<double,10>, 10>, 10> chi={};  
}

void set_initial_conditions(Grid& g);

int main () {
  Grid g();// greate object
  set_initial_conditions(g);// set the initial conditions.  
  return 0;
}

void set_initial_conditions(Grid& g) {
  std::cout<<"set initial conditions"<<std::endl;
}

When compiling with

c++ -o minimal_example minimal_example.cpp -std=c++17

I get the following error message:

minimal_example.cpp: In function ‘int main()’:
minimal_example.cpp:22:26: error: invalid initialization of reference of type ‘Grid&’ from expression of type ‘Grid()’
   22 |   set_initial_conditions(g);
      |                          ^
minimal_example.cpp:18:35: note: in passing argument 1 of ‘void set_initial_conditions(Grid&)’
   18 | void set_initial_conditions(Grid& g);
      |                             ~~~~~~^
jojo123456
  • 341
  • 1
  • 3
  • 11
  • 2
    `std::array, 10>, 10> chi={};` this line in your default constructor shadows the member variable instead of initializing it. You can just leave the default constructor blank. As for the actual question, looks like the most vexing parse. Replace `Grid g();` with `Grid g;` or `Grid g{};`. – Nathan Pierson Jun 12 '21 at 02:42
  • This particular anomaly trips up so many folks (beginners and experienced devs alike) that it has its own name. The relevant search term is "most vexing parse". – Silvio Mayolo Jun 12 '21 at 03:22

1 Answers1

1

Try to use:

// Create object.
Grid g;

Instead of:

Grid g();// create object

Or even something like:

Grid *g = new Grid(); // Heap allocation.
set_initial_conditions(*g);

delete g; // Later manual memory release.

Edit -- also replace your constructor's line:

std::array<std::array<std::array<double,10>, 10>, 10> chi={};  

With something like:

this->chi = {};

Note that many languages don't need you to write this explicitly, but recommend it to prevent conflicts.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
  • It's not related to compiler optimizations, it's the [most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse). The compiler is interpreting `Grid g();` as the declaration of a function, `g`, which takes no arguments and returns a `Grid`. – Nathan Pierson Jun 12 '21 at 02:45
  • You are right, normal types don't have parenthesis (but the error says `type ‘Grid()’`), so, it really is treated as a function declaration. – Top-Master Jun 12 '21 at 02:56