Cant create object in C++

Carlis

Senior member
May 19, 2006
237
0
76
Hi. I am trying to create an object in c++ but I'm doing terrible. I have tried the following code;

#include <iostream>
#include <fstream>
#include <math.h>


int main (int argc, char * const argv[]) {
using namespace std;

tst test; //error! tst was not declared in this scope. & expected ';' before test end comment//

double a=tst.input(9);
cout << a;

return 0;
}
//--------- tst.cpp

class tst{
public:
double input(double d);
};
double tst::input(double d){
return(d+1);
}

What did I miss?
 

nickbits

Diamond Member
Mar 10, 2008
4,122
1
81
this:
class tst{
public:
double input(double d);
};

needs to be in a .h file and #included in your main file
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
For your example, it literally *cannot* find the definition of "tst" (it doesn't automatically look ahead). To fix this, either place the definition in an external file and #include it, or move its declaration above your main method.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
As the others have said, it's the order of your declarations. It's best to learn to think of C/C++ files like the compiler sees them: read from top to bottom, and when you encounter #include treat the referenced file as if its contents replaced the "#include" in the text. Any name that you haven't encountered as you read from top to bottom, pulling in the included files, is a name that the compiler doesn't know about either.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Do this instead:
#include <iostream>
#include <fstream>
#include <math.h>

class tst{
public:
double input(double d);
};

int main (int argc, char * const argv[]) {
using namespace std;

tst test; //error! tst was not declared in this scope. & expected ';' before test end comment//

double a=tst.input(9);
cout << a;

return 0;
}

//--------- tst.cpp


double tst::input(double d){
return(d+1);
}

... or better yet put the class declaration into test.h and #include as others have suggested.