-8
#include<string.h>

int a = 2;

string str = to_string(a);

I want to know that in C++ whenever we want to call a library function we use

library_object.function_name() notation. But here we are directly using to_string() function without the using object. So my question is why we are not calling to_string() function like

string_object.to_string();

Also please specify what's the difference between the calling function here with and without the object.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
Pawandeep Singh
  • 830
  • 1
  • 13
  • 25
  • 4
    `` doesn't contain `std::string`. – Incomputable May 17 '17 at 14:41
  • 3
    Please read a [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282) or at least the [documentation](http://en.cppreference.com/w/cpp/string/basic_string/to_string) for the functionalities you use. – nwp May 17 '17 at 14:42
  • 1
    It's all about [functions](http://en.cppreference.com/w/cpp/language/functions) vs [member functions](http://en.cppreference.com/w/cpp/language/member_functions). – HolyBlackCat May 17 '17 at 14:44
  • `to_string` is supposed to return a string from the number you passed, so it would be rather strange if you would first need a string instance before you can call it – 463035818_is_not_an_ai May 17 '17 at 14:55

1 Answers1

3

You're making this way more complicated than it needs to be.

std::to_string is a function. Just a function. It's taking an int and giving back a std::string.

Here's another function:

void foo()
{
   // hello!
}

You don't need to make functions be member functions. C++ isn't just an object-oriented language.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055