C++ modifying struct values from function by reference (potentially compile order issue)


I've been doing a fair amount of reading on passing a struct member to a function. However if someone could clarify where I am going wrong I would appreciate it. I predict this is more a compile order / definition error than anything, although there may be syntax errors also.

As I understand it, I am able to modify the struct members data, and avoid any copying by passing as a reference (in this case NOT a pointer). This method will also allow me to keep the dotted notation for accessing individual members inside the function.


// include headers
struct foo{
  int a;
  int b;

int main(){
  foo_data.a = 1; // assign some values to the member in standard format.
  foo_data.b = 2;

  // should this be &foo_data, am I passing by value here as it is
  // or is the declaration taking care of that? 


void function(foo &) // function declaration reference of type foo


void function(foo &foo_data) // function definition reference of type foo
  foo_data.a; // should == 1
  foo_data.b; // should == 2

The errors typically relate to undeclared identifiers, being foo_data. Do I need to tell tell the declaration in functions.h I am passing it a struct, or in fact an int (reference?)


Best Solution

The class definition for foo must be visible to both main and function. Do it like this:

// File foo.hpp

struct foo { int a; int b; };
void function(foo &);

// File main.cpp

#include "foo.hpp"

int main()
    foo foo_data;
    foo_data.a = 1;

// File foo.cpp

#include "foo.hpp"

void function(foo & x)
     // use x.a, x.b etc.

If your function only needs to read the values, you can declare it with a foo const & argument.

Related Question