Creating a class object in c++

前端 未结 8 2172
离开以前
离开以前 2020-12-07 11:08

First i am from JAVA.

In java we create class object like this.

Example example=new Example();

The Example class can have constructor

8条回答
  •  旧时难觅i
    2020-12-07 11:56

    1)What is the difference between both the way of creating class objects.

    First one is a pointer to a constructed object in heap (by new). Second one is an object that implicitly constructed. (Default constructor)

    2)If i am creating object like Example example; how to use that in an singleton class.

    It depends on your goals, easiest is put it as a member in class simply.

    A sample of a singleton class which has an object from Example class:

    class Sample
    {
    
        Example example;
    
    public:
    
        static inline Sample *getInstance()
        {
            if (!uniqeInstance)
            {
                uniqeInstance = new Sample;
            }
            return uniqeInstance;
        }
    private:
        Sample();
        virtual ~Sample();
        Sample(const Sample&);
        Sample &operator=(const Sample &);
        static Sample *uniqeInstance;
    };
    

提交回复
热议问题