Pointers to classes question

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;
}
can you use code tags please?

Your first question:
You are defining a constructor and copy constructor in two ways, one using an initialisation list:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
and the other using older style conventional intialisation in the body of the ctor and copy ctor.
why do we allocate memory for the pointer?


Because you are creating a new string as it's a copy constructor. You new object has to have it's own variables.
why do we allocate memory for the pointer?

In order to "use" it. It is a pointer, and so must be pointing to something, something we create dynamically on heap.
Example4 (const string& str) : ptr(new string(str)) {}

this creates dynamically a string object for ptr to point to, by calling the copy constructor of std::string, and assigning the value of str to the newly created string.

Aceix.
Thank you for the answer

Could you check also this topic for an answer,please?
http://www.cplusplus.com/forum/general/141227/
Topic archived. No new replies allowed.