Pass struct to class

I am trying to pass a struct to a class so the class can use the member values. I am only including an abstract because the main code will be huge. I do not want to create the struct in the class because the struct will be created once from a file and there will be up to 4000 instances of the class, all of which will use part of the struct.

The main cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "myClass.h"
#include <iostream>
using namespace std;

struct foo
{
	int num;
	double dbl;
};

int main(int argc, _TCHAR* argv[])
{
	foo bar;
	bar.dbl=3.14;
	bar.num=42;
	baz qux(bar);	//bar needs to be passed here
	cout<<qux.getSum()<<endl;
	return 0;
}


The header:

1
2
3
4
5
6
7
8
9
class baz
{
public:
	baz(const foo&);	//This is where type of bar (foo) is declared
	void setSum(int, double);
	double getSum();
private:
	double sum;
};


The class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "myClass.h"
#include <iostream>
using namespace std;

baz::baz(const foo& blah)	//this is where bar is called
{
//	setSum(num,dbl);
	setSum(blah.num, blah.dbl);
}

void baz::setSum(int num, double dbl)
{
	sum=num*dbl;
}

double baz::getSum()
{
	return sum;
}


What am I doing wrong here?
foo has not been declared on line 4 in myClass.h so the compiler will give you an error. You only have a reference to a foo so it doesn't need the full class definition of foo. A forward declaration is enough.
struct foo;

In myClass.cpp you are accessing the members of foo so foo needs to be defined before you can do that. Put the definition of foo inside a header file and include it in myClass.cpp.
Perfect, didn't think to put the struct into a separate header. Thanks.
Topic archived. No new replies allowed.