Two ways to instantiate a C + + class

Source: Internet
Author: User

C++

There are two ways to instantiate a class:

To define objects directly:

First define a class:

Class A

{

Public

A ();

Virtual ~a ();

...

...

};

class implementation slightly.

When used:

A;

A.

member functions;

A.

member variables;

A

is an object.

A method for defining a pointer to a class: a *p = new A; p-> member function; p-> member variable;
Finally, don't forget to destroy the object: delete[] A;
A is created and released by the system, you don't have to worry about a memory leak, but the life span is only in curly braces in the region, and curly braces are useless. P is a pointer, to release itself, with bad very dangerous, with good powerful, because he can be assigned to the global variables, all of a sudden from the local variable into a global variable, but also the object as a function return value.
A;
A * a = new A ();
The above two methods can realize the instantiation of the class, there is the difference between the new:

1. The former allocates memory in the stack, which is dynamic memory allocation, which makes no difference in general applications, but dynamic memory allocation increases the controllability of objects. 2. Do not add new to allocate memory in the Stack 3. Large program with new, small program directly apply 4. Just allocating objects to the stack memory
5.new must delete, no new system will automatically reclaim memory

Two ways to instantiate a C + + class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.