Hello everybody,
I'm hatem faheem a student in Cairo university , Faculty of Engineering , Computer departement
I have a question in the C++ string class constructor <string>
that's the code

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s0 ("Initial");
    string s1 (s0,3);
    string s2 ("Initial",3)

    cout<<"s1 : "<<s1<<"\n";
    cout<<"s2 : "<<s2<<"\n";

    return 0;
}

After excution we will find that
* s1 : tial
* s2 : Ini

which means that s1 was initialized by s0 starting from index 3
but s2 was intialized by first 3 caharcters from s0

what's the diffrence ?????
and why they aren't same ????

Thanks,

Recommended Answers

All 3 Replies

Line 8 of your code is:

string constructor (string str, int number)

Line 9 of your code is:
string constructor (char* arr, int number)

It's been awhile since I wrote in c++, but i think you can understand this.
The point is that if you type "Initial", that's not object, it's array of char's

A "String Literal" is a null-terminated array of char (a C-Style string), it is not a C++-Style string object. This is an important distinction when declaring C++ std::string objects because there are several different overloads of the std::string constructor:

The declaration of s0 calls string ( const char * s ); The declaration of s1 calls string ( const string& str, size_t pos, size_t n = npos ); The declaration of s2 calls string ( const char * s, size_t n ); Notice the second argument of the constructor called by s1. It is a position argument, not a count argument. The count is determined by the third argument, which you didn't provide. As a result it is given a default value.

Source.

I got it :)
Thank you very much :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.