Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

ID: 659041 • Letter: I

Question

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?

Explanation / Answer

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote