-4

I have this piece of code that allocates and constructs an object:

#include <iostream>    
#include <new>          

struct MyClass {
  int data;

};

int main () {

  struct MyClass *p1=new MyClass;


  return 0;
}

So,if i understand correctly p1 is a pointer to a memory location where a Myclass Object is stored.So if i want for this particular object to update the int data value how can i do it?

  • 1
    _"So if i want for this particular object to update the int data value how can i do it?"_ What about `p1->data = 42;`? – πάντα ῥεῖ May 19 '19 at 20:16
  • 3
    `p1->data = 42;`. And [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?r=SearchResults&s=1|836.0633) should be a priority at this point. edit: @πάνταῥεῖ I swear to God I didn't see your assignment before posting mine. It really is the answer to everything. – WhozCraig May 19 '19 at 20:16
  • @WhozCraig _" I swear to God I didn't see your assignment before posting mine."_ Seems we're nerds ;-D ... – πάντα ῥεῖ May 19 '19 at 20:19
  • 1
    `struct MyClass *p1=new MyClass;` note that in `c++` you don't need the `struct` part of that. `MyClass *p1=new MyClass;` is sufficient. – drescherjm May 19 '19 at 20:26
  • 1
    You almost never need `new` and `delete` in modern C++. Consider them an advanced feature. If the object doesn't need to live longer than the nearest `{}` block, use an ordinary definition `MyClass obj1;`. If it does need to live longer, use `auto p1 = std::make_unique();` or `auto p1 = std::make_shared();`. – aschepler May 19 '19 at 20:34
  • @aschepler Is p1 an object or a pointer to an object's location? – Epitheoritis 32 May 19 '19 at 20:37
  • 1
    @Epitheoritis In my examples `p1` is either a `std::unique_ptr` or a `std::shared_ptr`. Both of these are class objects, which act much like raw pointers (you can do `*p1` and `p1->data`). – aschepler May 19 '19 at 20:39

1 Answers1

1

Members of objects without pointers are accessed by . I hope you know that, members of class pointers are accessed by ->. In your case

p1->data = 55