Tom Lilletveit
Tom Lilletveit

Reputation: 2002

c++ string :: npos is it calling the string class?

I am new to C++, moving from Java and wondering about this:

        pos = result.find(remove[i]);  
        if (pos == string::npos)

is it calling the string "superclass"? I am confused if it is calling the class itself accesing the constant "npos" how does it know which instance of the class it is if I have several string variables declared in my function?

Upvotes: 1

Views: 935

Answers (2)

Roee Gavirel
Roee Gavirel

Reputation: 19453

npos is static member of string.
Static members in C++ are created once per program and are shared by all instances of the same class. but also accessible without instantition of the class.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258638

npos is not bound to an instance, but to the class itself. It's a static member. There are static members in Java as well.

21.4 Class template basic_string [basic.string]

[...]

namespace std {
template<class charT, class traits = char_traits<charT>,
class Allocator = allocator<charT> >
class basic_string {
  public:
    //...
    static const size_type npos = -1;
    //...
};

std::string is a specialization of basic_string.

Upvotes: 5

Related Questions