Why should I use a pointer rather than the object itself?

后端 未结 22 1647
予麋鹿
予麋鹿 2020-11-21 23:26

I\'m coming from a Java background and have started working with objects in C++. But one thing that occurred to me is that people often use pointers to objects rather than t

22条回答
  •  旧巷少年郎
    2020-11-21 23:58

    I will include one important use case of pointer. When you are storing some object in the base class, but it could be polymorphic.

    Class Base1 {
    };
    
    Class Derived1 : public Base1 {
    };
    
    
    Class Base2 {
      Base *bObj;
      virtual void createMemerObects() = 0;
    };
    
    Class Derived2 {
      virtual void createMemerObects() {
        bObj = new Derived1();
      }
    };
    

    So in this case you can't declare bObj as an direct object, you have to have pointer.

提交回复
热议问题