Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with External Class in modular program 2

Status
Not open for further replies.

BigKeeya

Programmer
Nov 8, 2003
6
US
I am trying to create a modular program. In one module (clss.cpp) I have a class (named score). How do I access it from my main.cpp file. The keyword "extern" only works for functions and variables (My make file links both files correctly).

code:

clss.cpp

class score
{
private:
int points;


public:
int show_money(void) {return (points);}
score();
};

inline score::score()
{
int points=1000;
}


main.cpp

using namespace std;
extern class score;

int main()
{
score points;

cout<< &quot;Score:&quot; << points::show_money() << &quot;\n&quot;;

//system(&quot;PAUSE&quot;);



return (0);
}


I get an error stating that extern can only be used for functions and variables. So how do I reference a class in another module (or file)? Any help would be greatly appreciated.
 
Take the class definition (
Code:
class score { ... };
) out of the .cpp file, put it in a header file, then include it in your main .cpp file.


Don't forget #include guards in your header. e.g.

Code:
#ifndef BLAH_H
#define BLAH_H
...
#endif

It won't matter much for a small project, but get in the habit of doing it anyway.
 
clss.h
#ifndef CLSS_H
#define CLSS_H

class score
{
public:
int show_money(void) {return (points);}
score();

private:
int points;
};

#endif


clss.cpp
#include &quot;clss.h&quot;

score::score()
{
int points=1000;
}


main.cpp
#include &quot;clss.h&quot;

using namespace std;

int main()
{
score points;

cout<< &quot;Score:&quot; << points::show_money() << &quot;\n&quot;;

return (0);
}



Hope that helps ya...

Skute

&quot;There are 10 types of people in this World, those that understand binary, and those that don't!&quot;
 
oh, spotted a mistake...

change:

cout<< &quot;Score:&quot; << points::show_money() << &quot;\n&quot;;

to...

cout<< &quot;Score:&quot; << points.show_money() << &quot;\n&quot;;

Skute

&quot;There are 10 types of people in this World, those that understand binary, and those that don't!&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top