To Use Classes in C++

Oct 26, 2016 at 6:43am
Hi I have written a simple class in C++ but I am not able to use this in main function.

#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, _TCHAR* argv[])
{
Display display;
//std::string result = display.getText();
}

class Display
{
public :
Display()
{
m_value = "Intial Value";
}
~Display();
void setText(const std::string& value)
{
//value = m_value;
}
std::string getText()
{
return m_value;
}
private :
std::string m_value;
};

Getting below Errors...
Error 1 error C2065: 'Display' : undeclared identifier
Error 2 error C2146: syntax error : missing ';' before identifier
Error 3 error C2065: 'display' : undeclared identifier
Oct 26, 2016 at 6:49am
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
int main(int argc, _TCHAR* argv[])
{
Display display;
//std::string result = display.getText();
}

class Display
{
public :
Display()
{
m_value = "Intial Value";
}
~Display();
void setText(const std::string& value)
{
//value = m_value;
}
std::string getText()
{
return m_value;
}
private :
std::string m_value;
};


Should be :
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
class Display
{
public :
Display()
{
m_value = "Intial Value";
}
~Display();
void setText(const std::string& value)
{
//value = m_value;
}
std::string getText()
{
return m_value;
}
private :
std::string m_value;
};

int main(int argc, _TCHAR* argv[])
{
Display display;
//std::string result = display.getText();
}
Oct 26, 2016 at 7:08am
In addition, preferable, put your class definition at the top before the main block. Also, it seems you're using MS Visual studio. Nonetheless, there's no need preceding the call to string type with 'std::', if you've "using namespace std" statement before main block.
Oct 26, 2016 at 8:46am
With suggestion given above, I am getting below errors.
Error 1 error LNK2019: unresolved external symbol "public: __thiscall Display::~Display(void)" (??1Display@@QAE@XZ) referenced in function _main
Error 2 error LNK1120: 1 unresolved externals
Oct 26, 2016 at 8:48am
~Display();

Should be :
~Display() { /*An empty function with no code*/ }
Last edited on Oct 26, 2016 at 8:49am
Oct 26, 2016 at 8:53am
The reason is that you did not implement ~Display() (the body is missing). You can actually omit the destructor if there is nothing to do (the compiler will generate one for you).

crosslink wrote:
there's no need preceding the call to string type with 'std::', if you've "using namespace std" statement before main block.
I wouldn't recommend that. The namespace is there for a good reason: Avoiding names clash.
Topic archived. No new replies allowed.