I was reading a book on c++ when I encountered the following example:
#include <iostream>
#include <string>
using namespace std;
int main () {
const char *message = "how do you do\n";
string s(message);
cout << s << " and its size:" << s.size() << endl;
}
I wanted to know what exactly does it do. How can we pass a variable inte another variable as done in s(message)? Thanks in advance
s(message)
actually calls the constructor of std::string
, which constructs a new object of this type from the given character array pointed to by message
. s
is just an arbitary name given to the string object. std::string
is C++'s idiomatic object for working with strings, it is usually preferred over raw C strings.
Consider this simple sample:
// Declare a fresh class
class A {
public:
// a (default) constructor that takes no parameters and sets storedValue to 0.
A() {storedValue=0;}
// and a constructor taking an integer
A(int someValue) {storedValue=someValue;}
// and a public integer member
public:
int storedValue;
};
// now create instances of this class:
A a(5);
// or
A a = A(5);
// or even
A a = 5;
// in all cases, the constructor A::A(int) is called.
// in all three cases, a.storedValue would be 5
// now, the default constructor (with no arguments) is called, thus
// a.storedValue is 0.
A a;
// same here
A a = A();
std::string
declares various constructors, including one that accepts a const char*
for initialization - the compiler automatically chooses the right constructor depending on the type and number of the arguments, so in your case string::string(const char*)
is choosen.
That is actually one of the constructors of std::string
.
In C++, you can create objects a few different ways.
std::string s = "Hello"; // implicit constructor using const char *
std::string s = std::string("Hello"); // invoke the const char* constructor of std::string
std::string s("Hello"); // another way to do the stuff above
There are more ways than that, but just to demonstrate how you could create this std::string
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With