Classes and objects in C + + (ii)

Source: Internet
Author: User

One, the dynamic establishment and release of objects

1. What is the dynamic creation and release of objects

Usually we create objects that are created by the C + + compiler for us in stack memory, and we cannot manage the lifecycle of them. So we need to build the object dynamically, so we need to create the object in heap memory and dispose of the object. The malloc () function and the free () function are provided for us in the C language to give us a way to allocate variables in heap memory, but the new and delete keywords are introduced in C + + to let us dynamically create and release variables.

2.new and Delete keywords

    • The new keyword is used to create variables in heap memory in the form of: type * ptr = new Type (constant/expression); The constants/expressions in its argument list can be used to initialize variables or omit to write. Its return result is a pointer of that type. Returns a null pointer if the memory allocation fails.
    • The DELETE keyword is used to release memory created with the New keyword, in the form of delete ptr (the free array must be bracketed, delete [] ptr).

3.new and delete keywords differ from malloc and free

    • When allocating memory, the new keyword invokes the constructor of the corresponding class based on the parameters it creates. The DELETE keyword will first call the class's destructor to release the memory defined in the object before releasing the memory.
    • The malloc and free keywords do not call the class's constructors and destructors.

Example 4.new and Delete keywords

# define _crt_secure_no_warnings# include<iostream>using namespacestd;classteacher{ Public:    Char*name; intAge ; Public:    /*no parameter constructor*/Teacher () {name=NULL; Age=0; cout<<"no parameter constructor is executed ..."<<Endl; }    /*Parametric Constructors*/Teacher (Char* Name,intAge ) {        /*allocating heap memory in a constructor*/         This->name =New Char[sizeof(name) +1]; /*Initializing member variables*/strcpy ( This-name, name);  This->age =Age ; cout<<"an argument constructor is executed ..."<<Endl; }    /*copy Constructor*/Teacher (ConstTeacher &student) {        /*Reallocate Memory*/         This->name =New Char[sizeof(name) +1]; /*Initializing member variables*/strcpy ( This-name, name);  This->age =Age ; cout<<"copy constructor is executed ..."<<Endl; }    /* Destructors*/~Teacher () {if( This->name! =NULL) {            Delete[] This-name;  This->name =NULL;  This->age =0; } cout<<"destructors are executed ..."<<Endl; }};intMain () {/*Create an int variable and release the*/    int* A =New int; int* B =New int( -); DeleteA; Deleteb; /*create a double variable and release*/    Double* C =New Double; Double* d =New Double(10.1); DeleteC; DeleteD; /*Create an array and release*/    Char* E =New Char[ -]; Delete[] e; /*create an object and release*/Teacher* STU1 =NewTeacher ("Wang Gang", A); cout<<"Name:"<< Stu1->name <<", Age:"<< Stu1->age <<Endl; Teacher* STU2 =NewTeacher (); Deletestu1; DeleteSTU2; /*create objects with malloc and free and cannot call their constructs and destructors*/Teacher* STU3 = (Teacher *)malloc(sizeof(Teacher));  Free(STU3);}

Two, static member variables and static member functions

1.static keywords

The static keyword is used to declare a member in a class to be a static property. When a member is decorated with the static keyword, the object created by the class shares the static member. No matter how many objects are created, the member has only one instance. A static member is a class-related behavior that is not related to the object of the class.

2. The concept of static members

A static member is a shared member of all objects of a class, not a member of an object, which does not occupy storage space in the object, which belongs to the entire class and not to a specific object, so a static member variable cannot be initialized inside the class and must be initialized outside of the class. For example, defining a student class, the total number of student objects can be declared as static, in the construction method, the variable is added 1, so as to count the number of student objects.

3. Summary of static member variables

    • Static member variables can be defined with the static keyword, but initialization must be initialized outside of the class.
    • Static member variables can be accessed and modified by objects of classes and classes.
    • Static member variables follow the class's access control principle, and if private, they can be accessed only within the class and when initialized outside of the class, no longer accessed by other means.

4. Summary of static member functions

    • Static member functions are defined with the static keyword, where static member variables and static member functions can be accessed, but normal member variables and member functions are not allowed because ordinary members belong to the object and do not belong to the class. Levels are different. However, static members can be accessed in normal members.
    • When a static member function is defined in a class, but is implemented outside of the class, no additional static keywords are required.
    • The static member function does not have the this pointer.

5. Static member Focus Induction

    • Static members are the owners of objects of classes and classes, so static member variables cannot be initialized inside a class, and must be initialized outside of the class.
    • Static members still follow the Private,protected,public access control principle.
    • There is no this pointer in a static member function, no access to normal member variables and member functions, access to static member variables and member functions, but ordinary members can be accessed by passing objects.

6. Static Member Variable Demo

# include<iostream>using namespacestd;classmystudent{Private:    Static intCount/*total number of student objects*/    Charname[ -]; intAge ; Public:    Static intN; Public: Mystudent (Char* Name,intAge ) {strcpy ( This-name, name);  This->age =Age ; Mystudent::count++;/*number of students plus 1*/    }    voidGetCount ()/*ordinary member functions access static member variables*/{cout<<"Total Students:"<< Mystudent::count <<Endl; }};/*static member variable initialization*/intMystudent::count =0;intMystudent::n =Ten;intMain () {/*test static member variables*/mystudent Student1 ("Wang Gang", A);    Student1.getcount (); /*object and class methods access static member variables*/STUDENT1.N= -; Mystudent::n= $;}

7. Static member function demo

# include<iostream>using namespacestd;classtest{Private:    intm; Public:    Static intN; Public:    voidSetm (intm) { This->m =m; /*accessing static member functions*/test (); } Public:    Static voidxoxo (); Static voidTest () {n= -; //m = 10; access to normal member variables is not allowed//int c = Getm (); access to ordinary member functions is not allowed//this->m = +; this pointer does not existcout <<"static void Test () function ..."<<Endl; }};/*initializing static members*/intTest::n =Ten;/*class declaration, out-of-class implementation*/voidTest::xoxo () {cout<<"static void Test::xoxo"<<Endl;}intMain () {Test T; /*ordinary member functions access static member functions*/T.setm (Ten); /*How member functions are called*/t.test (); Test::test ();}

Classes and objects in C + + (ii)

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.