简体   繁体   中英

Why memory is not allocated to class when we create pointer type object?

I am little bit curious about that why memory is not allocated to a class or structure when we create pointer type object ?

For example :-

class A
{
    public:

    void show()
    {
        cout<<" show function "<<endl;  
    }

};
int main()
{
A *a;
a->show();
   return 0;
};

Because pointers and memory allocation are a priori completely unrelated. In fact, in modern C++ it's downright bad to use pointers to point to manually allocated memory directly.

In most cases, pointers point to existing objects – that's their purpose: to provide indirection . To reiterate: this is completely unrelated to memory allocation.

If you want to directly have an object you don't need a pointer: just declare the object as-is (= by value):

A a;
a.show();

This code:

A *a;
a->show();

just declares a pointer of type A* . Pointer alone is nothing but a variable that holds an address of some memory in it, ie it just points somewhere, nothing else. Pointer of type A* means that it points to memory, where an instance of type A is expected to be found.

a->show(); then just relies on this "expectation", but in fact it just uses uninitialized pointer, which results in undefined behavior .


This could be either solved by dynamically creating an instance of A :

A *a = new A();
a->show();

(which however gives you unpleasant responsibility for cleaning up this memory by calling delete a; ) or even better: using an object with automatic storage duration instead:

A a;
a.show();

In the second case, an instance of type A is created automatically and its lifetime is tied to the scope, in which it has been created. Once the execution leaves this scope, a is destructed and memory is freed. All of that is taken care of, without you worrying about it at all.

Allocating a pointer does not equate to allocating an object. You need to use new and instantiate an object on the heap, or create the object on the stack:

A* a = new A();
// Or
A a;
A* aPntr = &a;

Pointer is not an object, it's just a link that points somewhere. The reason to use them is that you can dynamically change what they're pointing to.

A a;
A b;
A *pA;

{
    bool condition;
    // set condition here according to user input, a file or anything else...

    if(condition)
        pA = &a;
    else
        pA = &b;
}

Now I don't have to take care about condition, it even doesn't have to exist anymore and still I can profit from the choice made above.

pA->show();

Or I can use pointer to iterate over an array:

A array[10];
for(A* pA = array; pA < array+10; pA++)
{
    pA->show();
}

(Note I used the original declaration of class A in both examples altough more meaningful it would be if each object of class A contained its specific information.)

There may not be one single reason for A *a; not to allocate an instance of A . It would be at odds with how C++ is designed. I would be somewhat surprised if Stroustrup considered it for long enough to identify a definitive reason not to do it.

A few different ways to look at it:

  1. You didn't ask for an object of type A , so you don't get one. That's how C and C++ work.
  2. A pointer object is an object that holds an address. You may as well ask why stationary manufacturers don't build a house when they manufacture an envelope, as ask why C++ doesn't allocate an object to be pointed at when you define a pointer.
  3. There are many ways to allocate memory. Supposing that memory was going to be allocated, which one would you like? You could argue that in C++ new would be a sensible default for class types, but then it would probably be quite confusing either if char *c; called new char (because the behavior would be different from C) or if char *c; didn't allocate memory at all (because the behavior would be different from char *A; .
  4. How and when would the memory be freed? If it's allocated with new then someone is going to have to call delete . It's much easier to keep things straight if each delete corresponds to a new , rather than each delete corresponding either to new or to defining a pointer with implicit memory allocation.
  5. A pointer can be the location of an object, but it isn't always (sometimes it's null, sometimes it's off-the-end of an array). The object can be dynamically allocated but doesn't have to be. It would be very unhelpful of the language to make a pointer point to an object in cases where you don't need it. Therefore the language gives you the option not to allocate memory when defining a pointer. If you don't want that, then you should initialize the pointer with the result of a call to the memory-allocation mechanism of your choice.

You just create a pointer *a, but not allocate memory for it.

you should use A *a = new A();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM