mercredi 24 décembre 2014

The difference between these two


I was reading about copy constructors for structs and i found this example:



#include <iostream>
#include <string>

using namespace std;

struct SomeData {

int * pd;
string id;

SomeData(SomeData & ref) {
cout << "Copy Constructor called" << endl;
pd = new int (*ref.pd) ;
id = "Copy Constructed";
}

SomeData(string name) {
pd = new int(0) ;
id=name;
cout << "Constructor for " << id << endl;
};

~SomeData() {
cout << "Destructor for " << id << endl;
delete pd;
}
};

int main() {
SomeData s("First") ;
*s.pd =9;
SomeData s2=s;
cout << *s2.pd << endl;
return 0;
}


in the main , the variable pd of SomeData is accessed using the dereference, but why is that, isn't the correct way is



s->pd=9;


why was it written like that in the example ?





Aucun commentaire:

Enregistrer un commentaire