Why do we need a pointer to a class if we can instantiate an object and access members of the class?


I'm a little confused here. If we can create a class object and access methods, then why a pointer to a class? Is there any benefit to this? And when do we use a pointer to a class and when do we instantiate an object?

Thank.

+3
source share
3 answers

You may not need a pointer to a class. If your class is small, it does not exhibit polymorphic behavior through the base class, or costs nothing to create an instance, you can probably just rip it on the fly and do it.

But in many cases, we need pointers because:

  • "", , . , , .
  • , , . , Singleton. Singletons "" , , - - . , ( ) "-".
  • , (, , ).
+9

, ?

, , . delete , , new. ( , . , new .)

class foo
{
    int a ;
};

foo obj1 ;
foo obj2 = obj1 ; // Copy construction. Both obj2, obj1 have it independent
                  // copy of objects. (Deep copy)

foo *obj3 = new foo ;
foo *obj4 = obj3 ; // Copy construction. However, both obj3, obj4 point to the 
                   // same object. (Shallow copy)

                   // You should be careful in this case because deletion of obj3
                   // makes obj4 dangling and vice versa.

?

Polymorphism, /.

?

. , , .

+7

One reason may be performance. Imagine you have 100 instances of a class. If you do not use pointers, and you want to do something like copying these instances from one container to another, there is quite a lot of overhead, since the copy constructor will need to be called on each of them. However, if you have pointers to these instances, then the only thing that really copies is the pointer, which makes the operation much faster.

+1
source

All Articles