+ 1

obj ptr no needs point to previous created obj?

when u create a obj ptr can access members without point to a created obj what happend, it creates an object implicitly? dont need create object explicitly then? advantajes ans disadvantajes? thx

7th Aug 2019, 12:56 AM
BinaryEden
BinaryEden - avatar
2 odpowiedzi
+ 2
Assuming you have a class class A { public: int x; A() { x = 39; std::cout << "Constructor called."; } }; and you do A* obj; std::cout << obj->x; This is equivalent to using an uninitialized variable. Your code will compile, but whatever happens next is undefined behavior. You should notice that the constructor was never called, meaning that no new object was created. Usually, when a pointer to an object is used, it is used alongside the new keyword to dynamically create an object to be pointed to. A* obj = new A(); std::cout << obj->x; delete obj;
7th Aug 2019, 2:17 AM
Fermi
Fermi - avatar
0
so its purpose is only didactic, to make examples
7th Aug 2019, 2:18 AM
BinaryEden
BinaryEden - avatar