I learn C ++ reading a tutorial. The "objects and pointers" part says that declaring a pointer to such an object:
SomeClass *ptrMyClass;
does nothing on its own. Only after defining an instance of the class does this make sense, for example:
SomeClass *ptrMyClass; ptrMyClass = new SomeClass;
Or combining them in:
SomeClass *ptrMyClass = new SomeClass;
My question is: why do we need to create an instance of SomeClass on the heap using "new"? So far, in the book, pointers always pointed to "normal" variables (for example, int, float ...) that were not created using the "new". Thanks.
++: ( ). :
void func() { // On the stack: Widget blah; // On the heap: Widget * foo = new Widget; delete foo; }
/ , , , / , . , , ( , ). blah , func(). . / ( , "" ), .
blah
func()
() , , . , , . , / ( ) .
, , , , , . delete, . ++ (, std::shared_ptr).
delete
std::shared_ptr
. , (.. ) . , .
: SomeClass , 'new'?
. . ,
SomeClass* ptrMyClass1; // An uninitialized pointer. // If an automatic object its value is indeterminate and // You have not defined what it points at. It should not // be used (until you explicitly set it to something). // If a static object then it is initialized to NULL // i.e. Global (or other static storage duration object). SomeClass* ptrMyClass2 = new SomeClass; // A pointer to a dynamically // allocated object. SomeClass objMyClass3; // A normal object SomeClass* ptrMyClass4 = &objMyClass3; // A pointer to a normal object
, .
, ( Java PHP- interface):
interface
class IMyAbstractClass { public: virtual int myFunction(void) = 0; }; class MyInheritedClass : public IMyAbstractClass { public: int myFunction(void) { // doSomething return 0; } };
, , , :
IMyAbstractClass * myInstance; myInstance = new MyInheritedClass;
, , IMyAbstractClass:
AnotherClass anotherObject(myInstance);
:
class AnotherClass { public: AnotherClass(IMyAbstractClass * instance) { // doSomething } };
.
SomeClass , ""?
. , :
SomeClass some; SomeClass* ptrMyClass(&some);
Source: https://habr.com/ru/post/1525710/More articles:converting time_point to a specific duration using a chronograph - c ++Programmatically building a query using the LINQ statement with an entity infrastructure - c #How does the Closure Compiler use type information to compile to speed JavaScript? - javascriptParallel read-only HashMap - javaNPM error when installing Google Coder on Raspberry Pi - node.jsHow to combine multiple Excel sheets from different files into one file - pythonCSS Creating transparency for changing divs, ease of hover - cssHow to provide SourceDictionary Source in WPF with folder structure - c #Phonegap / Android multiple actions created - androidHow does the overload function work at run time and why does overload? - c ++All Articles