gogoWebsite

Detailed explanation of C++ classes and objects (the difference between new and not new)

Updated to 2 days ago

1. Introduction to "Class"

In C++, "classes" are used to describe "objects", and the so-called "objects" refer to everything in the real world. Then the class can be regarded as an abstraction of similar things and find common points between these different things, such as bicycles and motorcycles. First of all, they all belong to "objects" and have certain similarities, and some differences, such as they all have mass, two wheels, and they all belong to means of transportation. "Every mass" and "two wheels" belong to the attributes of this object, and "both can be regarded as vehicles" belong to the behaviors that the object has, also known as methods.

A class is a user-defined data type, and the data of this type has certain behavioral capabilities, which is the method described in the class. Generally speaking, a class definition contains two parts, one is the properties of the class and the other is the methods it has. In the category of "human", everyone has their own name, age, date of birth, weight, etc., which are the attributes of human beings. In addition, people can eat, sleep, walk, and talk belong to human behaviors.

The "human" class described in the above examples is only some of the most basic attributes and behaviors of an object like human, and can be called the "base class" of humans. Let’s talk about some people with some professions, such as students. A student also has attributes that are not found in the "base class", such as schools, classes, and student numbers; they can also have behaviors that are not found in the base class, such as having to attend classes every day, requiring exams, etc.

The student class can be regarded as an extension of the base class, because it has all the properties and behaviors of the base class, and on this basis, some properties and behaviors that the base class does not have. Classes like "student" are called "derived classes" or "subclasses" of the base class "human". In the foundation of students, Shanghai can further expand other more advanced classes, such as "graduate students" classes.

At this point, we will no longer introduce other relevant knowledge in the category in depth.

Two: Use of classes

A class is a template for creating an object. A class can create multiple objects, each object is a variable of the class type; the process of creating an object is also called instantiation of the class. Each object is a concrete instance of the class, with member variables and member functions of the class.
Like structures, classes are just declarations of complex data types.No memory space occupied. The object is a variable of the data type of class, which occupies memory space.

Class declaration

Classes are user-defined types. If a class is to be used in a program, it must be declared first, or an existing class (class written by others, classes in the standard library, etc.). The C++ syntax itself does not provide the name, structure and content of the ready-made class.
A simple class definition:

class Stock { //class declaration

private: //Default keyword private

      std::stringcompany;

      longshares;

      doubleshare_val;

      doubletotal_val;

voidset_tot() { total_val = shares * share_val; } //The functions declared in the class automatically become inline functions

      //voidset_tot(); //defination kept separate

public:

      Stock();

      Stock(conststd::string &co, long n, double pr);

      ~Stock();

      voidacquire(const std::string &co, long n, double pr);

      voidbuy(long num, double price);

      voidsell(long num, double price);

      voidupdate(double price);

      voidshow() const; //promises not to change invoking object

}; //note semicolon at the end

This example creates a Stock class, which contains 4 member variables.
class is a keyword in C++, used to declare a class; immediately after the class keyword is our customized class name Stock; surrounded by { } is the class body. When declaring a classMember variables cannot be initialized, can only be assigned after the object is created.
A class can be understood as a new data type whose name is Stock. Unlike basic data types such as char, int, float, etc., Student is a complex data type that can contain basic types and has many features that are not found in basic types.

It should be noted that there is a semicolon (;) at the end of the class declaration, which is part of the class declaration, indicating that the class declaration is over and cannot be omitted.

Create an object

After declaring the Stock data type, you can use it to define variables, such as:

Stock s1 //Create an object

This statement declares a variable with the name s1 and the data type Stock. This and:

int a;  //Define the plastic variable

The statement defines an integer variable expression that means similar. And we call the variable s1 an object of the Student class.

When defining an object of a class, the class keyword can be requested or not. But out of habit we usually omit the class keyword, for example:

1.        classStock s1;  //Correct

2.         Stock s1;  //Same correct

When creating an object of a class, in addition to defining a single variable, you can also define an array or pointer. For example:

1.        Stock all_stock[100];

2.        Stock *pointer;

The first statement defines an all_stock array, which has 100 elements, each of which is of type Stock. The second statement defines a pointer of Stock type, which can point to a variable (object) of Stock type, and its usage is the same as a normal pointer.

Create objects while declaring a class

Similar to structs, you can declare the class first, then create objects, or you can create objects while declaring the class. As shown below:

class Person{

public:

//Member variable

char *name;

int age;

double weight;

 

//Member Function

void say(){

std::cout << "I am" << name << ",This year" << age << "year, weight" << weight << std::endl;

}

}p1, p2;

At this time, you can also omit the class name and create the object directly.

Directly defining objects is legal and allowed in C++, but it is rarely used and is not recommended.
A complete example:

Header file:

#ifndef PERSON_H_

#define PERSON_H_

 

class Person {

public:

//Member variables

      char*name;

      intage;

      doubleweight;

 

//Member function

      voidsay() {

std::cout << "I am" << name <<", this year" << age<< "year, weight" << weight <<std::endl;

      }

};

 

#endif  PERSON_H_

Source File

#include <iostream>

#include "";

 

int main() {

//Create an object

       Person p1;

="Zhang San";

       = 25;

       =60.00;

       ();

 

//Define pointer

       Person *p2 =&p1;

p2->name ="Li Si";

       p2->age =50;

       p2->weight= 68.94;

       p2->say();

 

       system("pause");

       return 0;

}

Running results:


public is a keyword in C++ that is used to modify member variables and member functions to indicate that they are public. Only member variables and member functions after public can be accessed by the created object. Without public, no members cannot be used after the object is created.

The main function first creates an object p1, and then defines a pointer variable of Person type. It can be found that, similar to structs, an object accesses member variables and member functions through the member selector ".", while a pointer variable accesses members through the pointer operator "->".

Note: The object pointer points to a concrete object, not a class. The following is written incorrectly:
Person *p1;

p1 = &Person;

The scope, visible domain and survival period of an object

The scope, visible domain and survival period of class objects remain the same as those of ordinary variables. When the object's survival period ends, the object is automatically revoked and the memory occupied is recycled. It should be noted that if there is a dynamic memory program applied for using new or malloc in the object's member functions, it will not be released. We need to clean it manually, otherwise it will cause memory leakage.

The difference between using new and not using new objects in C++

At first, when I first learned C++, I was not used to using new. Later, I looked at foreign programs and found that almost all I used new. Thinking about it, the difference is not too big, but in larger project designs, sometimes not using new will indeed bring many problems. Of course, this is all related to the usage of new.Create an object in new. After using it, you need to use delete to delete, which is similar to applying for memory.. Therefore, new is sometimes not suitable. For example, in frequent calls, using local new objects is not a good choice. Using global class objects or an initialized global class pointer seems to be more efficient.

1. The difference between creating a class object in new and not new

Below are some of the characteristics of new object creation that I have summarized:

Create new object requires pointer reception, initialization in one place, and use in multiple places

New object creation needs to be deleted after use

Create new objects directlyHeap space, while local objects do not use new to define them, use stack space

New object pointers are widely used, such as function return value, function parameters, etc.

Frequent calls are not suitable for new, just like new requests and frees memory.

2. Create class object instances in new

1. Example of creating an object in new:

CTest*  pTest = new  CTest();

delete pTest;

pTest is used to receive object pointers.

Without new, use the class definition declaration directly:

CTest  mTest;

This creation method does not require manual release after use, and this class of destructor will be automatically executed. The object applied for new will only execute the destructor when delete is called. If the program exits without delete, it will cause a memory leak.

2. Only define class pointers

This is very different from declaring objects without new. Class pointers can be defined first, but class pointers are just general pointers and no memory space is allocated to the object of this class before new. for example:

 

CTest*  pTest = NULL;

However, class objects created using the normal method have allocated memory space at the beginning of creation. And class pointer,If the object is not initialized, delete is not required.

3. New object pointer as function parameter and return value

Below is an example of writing casually, which is not very rigorous. It mainly illustrates that the class pointer is used as a return value and parameter.

#include<iostream>

using namespacestd;

 

class TestA {

public:

       int a;

       TestA() {

cout << "Default constructor of TestA" <<endl;

       }

       ~TestA() {

cout << "TestA's destructor" <<endl;

       }

};

 

class TestB {

public:

       int b;

       TestB() {

cout << "Default constructor of TestB" <<endl;

       }

       ~TestB() {

cout << "Destructor of TestB" <<endl;

       }

};

 

TestA* fun(TestB*pb) {

   TestA* pa = new TestA();

   pa->a = pb->b;

   return pa;

}

 

int main() {

       TestA* pa = new TestA();

       TestB* pb = new TestB();

       pb->b = 20;

       TestA* pRes = fun(pb);

       if(pa != NULL) {

         delete pa;

       }

       if(pb != NULL) {

         delete pb;

       }

       if(pRes != NULL) {

         delete pRes;

 

       }

 

       system("pause");

       return 0;

}

result: