Why use the β€œnew” when creating objects with related pointers?

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.

+4
source share
4 answers

++: ( ). :

void func()
{
    // On the stack:
    Widget blah;

    // On the heap:
    Widget * foo = new Widget;
    delete foo;
}

/ , , , / , . , , ( , ). blah , func(). . / ( , "" ), .

() , , . , , . , / ( ) .

, , , , , . delete, . ++ (, std::shared_ptr).

. , (.. ) . , .

+3

: 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
+2

, .

, ( Java PHP- 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
    }
};

-?

.

+2

SomeClass , ""?

. , :

SomeClass some;
SomeClass* ptrMyClass(&some);
+1

Source: https://habr.com/ru/post/1525710/


All Articles