1

I am new to C++. I was recently making a small program that uses classes in separate file. I also want to use the setter and getter (set & get) functions to assign value to a variable. The compiler gives me a weird error when i run the program. it says 'string' does not name a type. Here is the code:

MyClass.h

#ifndef MYCLASS_H   // #ifndef means if not defined
#define MYCLASS_H   // then define it
#include <string>

class MyClass
{

public:

   // this is the constructor function prototype
   MyClass(); 

    void setModuleName(string &);
    string getModuleName();


private:
    string moduleName;

};

#endif

MyClass.cpp file

#include "MyClass.h"
#include <iostream>
#include <string>

using namespace std;

MyClass::MyClass()  
{
    cout << "This line will print automatically because it is a constructor." << endl;
}

void MyClass::setModuleName(string &name) {
moduleName= name; 
}

string MyClass::getModuleName() {
return moduleName;
}

main.cpp file

#include "MyClass.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    MyClass obj; // obj is the object of the class MyClass

    obj.setModuleName("Module Name is C++");
    cout << obj.getModuleName();
    return 0;
}
Ajmal Razeel
  • 1,663
  • 7
  • 27
  • 51
  • `std::string moduleName;` – SergeyA Apr 14 '16 at 17:04
  • I didn't get it. which file should I modify? can u plz explain step by step. – Ajmal Razeel Apr 14 '16 at 17:06
  • I and a lot of other people will strongly recommend against trying to fix this by adding `using namespace std;` to the header. It doesn't always lead to pain, but it causes more grief than you likely want to put up with. More here: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice – user4581301 Apr 14 '16 at 17:06
  • SergeyA's point is that there is no such thing as `string`. But there is `std::string`. You are using the wring name. – user4581301 Apr 14 '16 at 17:07
  • 1
    @downvoters Find a good dupe or shut up. – πάντα ῥεῖ Apr 14 '16 at 17:31
  • @πάνταῥεῖ There's a close reason specifically for questions like these... "This question was caused by a problem that can no longer be reproduced or a simple typographical error." – hichris123 Apr 18 '16 at 20:13

1 Answers1

6

You have to use the std:: namespace scope explicitly in your header file:

class MyClass {    
public:

   // this is the constructor function prototype
   MyClass(); 

    void setModuleName(std::string &); // << Should be a const reference parameter
                    // ^^^^^
    std::string getModuleName();
 // ^^^^^    

private:
    std::string moduleName;
 // ^^^^^    
};

In your .cpp file you have

using namespace std;

which is grossly OK, but better should be

using std::string;

or even better yet, also using the std:: scope explicitly like in the header.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190