Hi all,

I created a string object and printed its size. Its always priniting output as 16. Why is it like that?
Can anyone give me idea about how string class is implemented.
I am using VC

string input;
cin>>input;
cout<<sizeof(input)<<input<<'\n';

>Its always priniting output as 16. Why is it like that?
Because that's the actual size of the object. The implementation probably looks something like this:

template <class T, class Traits = char_traits<T>, class Alloc = allocator<T> >
class basic_string {
public:
  // Lots and lots of interface stuff
private:
  size_type size;     // Probably a 32-bit type
  size_type capacity; // Probably a 32-bit type
  _buf_type buffer;
};

Where _buftype is likely defined as something along these lines:

struct _buf_type {
  T *base; // Beginning of buffer
  T *mark; // Helper pointer within buffer
};

The actual size of the string data itself is dynamic, so sizeof won't tell you how much memory has been allocated to the string. You can find that with the capacity member function.

Thanks Narue,

Is there any function to calculate the length of string object. From ur explanation I guess strlen wont work.

Yes, you find the manual / help pages which describe the string class.
This will detail the public interface to the class.

Say perhaps

string foo;
foo.length();

Both the length and size member functions will give you the length of the actual string. Why are there two functions that do the same thing? That's the effect of taking an existing (pre-standard) class and forcing it to fit within the new standard definition of a container class. There are lots of ways the string class is poorly designed, and this is one of them. ;)

This article has been dead for over six months. Start a new discussion instead.