Creating a class object in c++

前端 未结 8 2169
离开以前
离开以前 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 11:52

    Example example;
    

    This is a declaration of a variable named example of type Example. This will default-initialize the object which involves calling its default constructor. The object will have automatic storage duration which means that it will be destroyed when it goes out of scope.

    Example* example;
    

    This is a declaration of a variable named example which is a pointer to an Example. In this case, default-initialization leaves it uninitialized - the pointer is pointing nowhere in particular. There is no Example object here. The pointer object has automatic storage duration.

    Example* example = new Example();
    

    This is a declaration of a variable named example which is a pointer to an Example. This pointer object, as above, has automatic storage duration. It is then initialized with the result of new Example();. This new expression creates an Example object with dynamic storage duration and then returns a pointer to it. So the example pointer is now pointing to that dynamically allocated object. The Example object is value-initialized which will call a user-provided constructor if there is one or otherwise initialise all members to 0.

    Example* example = new Example;
    

    This is similar to the previous line. The difference is that the Example object is default-initialized, which will call the default constructor of Example (or leave it uninitialized if it is not of class type).

    A dynamically allocated object must be deleted (probably with delete example;).

提交回复
热议问题