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 member 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?
1
This is an example of operator precedence not giving quite the results you expect. The example has the code
*s.pd = 9;
which is equivalent to the following:
*(s.pd) = 9;
You query why it isn’t written as
s->pd = 9;
but this is equivalent to
(*s).pd = 9;
That is, the code in the example dereferences the value of pd that is a member of s, whereas the code you are asking about dereferences s (which is not legal as s is not a pointer and doesn’t have an overload for the “->” operator).
This is because “.”, the member selection operator binds more strongly than “*”, the dereference operator.
See http://en.cppreference.com/w/cpp/language/operator_precedence for a complete list; “.” has a precedence of 2, while “*” has a precedence of 3. Only “::” binds more strongly than “.”.