How to call a function using an object created in a class

Here is my code that I am using in three separate files:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//Header
  struct cheese
{
	cheese(int number1 = 5, int number2 = 5);
	int getNumber1(void);
	int getNumber2(void);
	int multiply(void);
	void setNumber1(int);
	void setNumber2(int);
private:
	int x;
	int y;
}win;

//.cpp
#include "cheese.h"

cheese::cheese(int number1, int number2)
{
	setNumber1(number1);
	setNumber2(number2);
}

int cheese::getNumber1(void)
{
	return x;
}

int cheese::getNumber2(void)
{
	return y;
}

int cheese::multiply(void)
{
	return getNumber1() * getNumber2();
}

void cheese::setNumber1(int number)
{
	x = number;
}

void cheese::setNumber2(int number)
{
	y = number;
}

//main()
#include "cheese.h"
#include <iostream>
using namespace std;

int main()
{
	cout << "Multiplication: " << win.multiply() << endl;
}


I am trying to use the "win" object from the "cheese" class to access the member function "multiply()." The only error message I am getting is "struct cheese win already defined in cheese object." I don't know how to fix this and I would like to know how I would use the "win" object of "cheese" class to call member functions. I am aware that I could create an object of the class by doing:

1
2
3
4
5
6
7
8
9
10
//main()
#include "cheese.h"
#include <iostream>
using namespace std;

int main()
{
	cheese object;
        object.multiply();
}


However I would prefer it if I could use the object already created in the class.
The problem is since you are creating a cheese object called 'win' inside the header, both your main file and cheese.cpp are trying to create a 'win' object separate and so you have your error.

You can only declare the object in one source file; if other files need to use the same one they need to declare it as extern.
Topic archived. No new replies allowed.