C++ Learning Note
Contents
Heap memory and Stack memory
Different ways to initialize pointers
int * a = #
create a pointer points to num on stack memoryCube * cube = new Cube;
create a pointer points to cube on heap memory
When deleting a pointer, we need to assign the pointer to
nullptr
even if the the memory will be released after the function is returnedPointer can use
->
to obtain the class attribute, otherwise we need dereference and use dot (cube->attribute
<=>(*cube).attribute)
1 2
int *x = new int; int &y = *x; //y is the alias of heap memory stored *x
Constructors
Default constructor/ Customized constructor
Copy constructor (copy constructors are invoked automatically)
Passing an object as a parameter (by value)
Returning an object from a function (by value)
Initializing a new object
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Cube::Cube(const Cube & obj) { length_ = obj.length_; std::cout << "Copy constructor invoked!" << std::endl; } int main() { Cube c; Cube b; Cube myCube = c; // copy constructor will be called b = c //copy constructor will not be called return 0; }
Assign constructor
Is a public member function of the class.
Has the function name operator=
Has a return value of a reference of the class’ type.
Has exactly one argument
The argument must be const reference of the class’ type.
1 2 3 4 5 6
Cube & Cube::operator= (const Cube & obj) { length_ = obj. length; std::cout << "Assignment operator invoked!"<< std::endl; return *this; }
Destructor (~). An destructor should neverbe called directly. Instead, it is automatically called when the object’s memory is being reclaimed by the system:
- If the object is on the stack, when the function returns
- If the object is on the heap, when delete is used
Author Zitao
LastMod 2021-12-27