First:
I don't understand
Example4() : ptr(new string) {}
Example4 (const string& str) : ptr(new string(str)) {}
I will write it is another way for you to explain:
Example4() {
ptr = new string;
}
Example4 (const string& str) {
ptr= new string(str); //I don't understand that line
}
Second:
why do we allocate memory for the pointer?
the example in link:
http://www.cplusplus.com/doc/tutorial/classes2/
// destructors
#include <iostream>
#include <string>
using namespace std;
class Example4 {
string* ptr;
public:
// constructors:
Example4() : ptr(new string) {}
Example4 (const string& str) : ptr(new string(str)) {}
// destructor:
~Example4 () {delete ptr;}
// access content:
const string& content() const {return *ptr;}
};
int main () {
Example4 foo;
Example4 bar ("Example");
cout << "bar's content: " << bar.content() << '\n';
return 0;
}