Search code examples
c++stringheader-filesprivatemember-variables

In C++ why is it that int variable can be declared as private data member of a class, but not string variable?


In C++ the following header file is legal

#ifndef    SAMPLE_H_
#define    SAMPLE_H_

class Sample {
    private:
        int number;
};

#endif

But the following header file is illegal

#ifndef
#define

class Sample {
    private:
        string name;
};

#endif

Why is it like that?

In my case I have the following header file:

Alphabet.h

#include <string>

#ifndef         ALPHABET_H_
#define         ALPHABET_H_


class Rhyme {

private:
    string a;

public:

    Rhyme ();

};

#endif

Alphabet.cpp

#include <iostream>
#include "Alphabet.h"

using namespace std;

Rhyme::Rhyme () {

    a = "A for Apple";
}

Main.cpp

#include <iostream>
#include "Alphabet.h"

using namespace std;

int main () {

    Rhyme rhyme;
    return 0;
}

Linux terminal command:

g++ *.cpp
./a.out

After this I am getting the following error:

Error:

    In file included from Alphabets.cpp:2:0:
Alphabet.h:10:2: error: ‘string’ does not name a type
  string a;
  ^
Alphabets.cpp: In constructor ‘Rhyme::Rhyme()’:
Alphabets.cpp:8:2: error: ‘a’ was not declared in this scope
  a = "A for Apple";
  ^
In file included from Main.cpp:2:0:
Alphabet.h:10:2: error: ‘string’ does not name a type
  string a;

I am trying to declare a string member variable in header file as private, and then initialize it from another file using constructor


Solution

  • In C++, int is a builtin keyword and is a valid type anywhere in the code. string is a class in the std namespace defined in the <string> header and may only be used if you include the header first.

    You should not use the using namespace directive in header files (namespace pollution), so you need to write std::string.

    Also, use the file name of your header (e.g. SAMPLE_H) for include guard:

    #ifndef SAMPLE_H
    #define SAMPLE_H
    
    #include <string>
    
    class Sample {
        private:
            std::string name;
    };
    
    #endif