Facebook Page Twitter Page LinkedIn Page
× C++ Tutorial C++ Advanced C++ Resources

The C++ string::capacity function is used to return size of currently allocated space to the string, expressed in terms of characters. The returned value is not necessarily equal to the string length. It can be greater than or equal to as compared to the string length, with the extra space required for the string object to optimize its operations.


size_type capacity() const;
size_type capacity() const noexcept;


No parameter is required.

Return Type

Returns size of currently allocated space to the string, measured in terms of number of characters it can hold.


In the below example, the string::capacity function is used find out the size of currently allocated space to the string MyString.

#include <iostream>
using namespace std;
int main (){
    string MyString = "Hello World!.";

    cout<<"The String is: "<<MyString<<"\n";
    cout<<"String length: "<<MyString.length()<<"\n";
    cout<<"String size: "<<MyString.size()<<"\n";
    cout<<"String capacity: "<<MyString.capacity()<<"\n"; 
    return 0;

A possible output could be:

The output of the above code will be:

The String is: Hello World!.
String length: 13
String size: 13
String capacity: 15

❮ C++ - String Functions