Cpp review 1

Important Keywords

  • const

Type Meaning Explanation
const int x constant variable Value of x must be initialized first
const int *x constant content; mutable pointer;
d
constant content pointer x points to.
address of pointer x is mutable.
x can be initialized after defintion
int * const x constant pointer;
mutable content;
pointer x must be initialized first;
const int* const x Constant pointer;
Constant content
x must be initialized first
const Class a constant class var content of member var of a can not be changed;
can not call not-constant functions;(avoid changing member values)
void func(const int x) const var as input function can not change the local variable;
const int& funct(x) return constant reference pointer using this reference can not change its content
const int funct(x) return constant var return a constant variable
int func() const constant member function Function is unable to change member values in the class
const MyClass c constant Class variable variable c can not call non-const member function and c can not change member variable values
  • define

    • Macro preprocesing keyword.
    • Different from const, #define doesn’t have data type
    • Compiler replaces the words only without checking the variable and its memory. E.g #define A B. Replace A with B only, compiler doesn’t check the type of A.
    • In C++ program, usually use const rather than define for security.
  • sizeof(x) / sizeof x

    • check number of bytes of variable based on data type
    • sizeof class_variable = sum of bytes of all member variables in class
    • in 64-bit machine, sizeof pointer = 8 bytes = 64 bits
  • static

    • static global var

      • only visiable to current file
      • data is stored in global memory, whereas local var is stored in stack and heap.
      • Automatically initialized as 0
      • Eg:
        1
        2
        static int a;
        int main(){...}
    • static local var

      • It is initialized once
      • stored in global memory without releasing memory until program terminates
      • can be used in local code block only.
    • static function

      • visible to current file only
      • can be defined in public, protected, private region.
    • static class member: used for private class info, rather than instance info

      • Different from common private member (which can be called and modified via this pointer), static class member DO NOT have this pointer

      • Only private and protected member can define static. Public member can not define static.
        However, static function can be defined in public region as well.

      • Can be called only by private/protected class function

      • Initialization for static member inside class requires const definition

      • Initialization for static member outside class requires that

        1. it can be initialized once.
        2. Initialization must be outside code block, like global variable
      • Example code:

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        class myclass{
        public:
        void func(){cout<<b;} // call private var inside member function
        private:
        static int a;
        //or
        static const int a =0;

        static int a=0;//wrong, a must be const
        static int b;
        }
        int myclass::b = 10; // way to initialize staic class member, like global var, but won't conflict global var.
        int main(){...}
    • external

      Tell the compiler that there is an function, whose implement of function is in other file.

    • inline

      • inline function tell the compiler to embed the code of the function into every place where the function is called. So, inline function reduce the time used to expand the function by using more memory.

      • Normal function in C/C++ is expanded by compiler only when they are call. This requires longer time to run program

      • Inline function has higher memory complexity and lower time complexity than normal function

      • Not suitable for construtor function (since it will generate lots of codes )

      • Not suitable for virtual function

      • inline function is unable to use render/loop operation

      • Note:

        1. Inline function doesn’t support loop and switch
        2. Usually, inline function is used when function has a few codes. (usually less than 10 lines)
    • typedef and #define

      • It is a sentence not command for compiler, so it requires “;” compared with #define
      • Compiler check the grammar and type of typedef, but doesn’t check type of #define
      • #define simply replaces the notation with new one, it doesn’t check the grammar or operation in definition
      • Example:
        1
        2
        3
        typdef struct A{...} B;     //define A as type B
        #define A B // define / replace B with A
        #define func(x) x*x
    • explicit

      • Require constructor to run explictly
        Eg:
        1
        2
        3
        4
        5
        6
        7
        c = myclass(1);
        //or
        c= (myclass) 12; // convert type explictly


        myclass c;
        c = 1; // Not allowed, need (myclass) 1
    • Using

      • Declaration of “using” keyword:
        It indicates the class we use is from std library.
        • Example:
          1
          using std::vector;
          It indicates the class vector is from std
      • Compile command:
        It tells the compiler to use the whole namespace (every element from this namespace)
        • Example:
          1
          using namespace std;

Variable type

  • global
  • local
  • static

Operators

  • Operator computes from right to left:
    • <condition-expression> ? <return if condition=__True__> : <return if condition =__False__>
      It returns value from right to left
    • =
  • Operator Priority
    • arithmetic operator: *, % , / are higher than +, -
    • Relationship operator: >, < , >=,<= are higher than !=, ==
    • logic operator: ! higher than &&, && higher than ||
    • logic bit operator: ~ higher than &, & higher than |

Grammar

  • a++ and ++a

    • a++: return another local variable contain value of a. Then a=a+1
    • ++a: a=a+1 and then return a.
    • Speed: a++ > a+=1 > a=a+1.
  • Switch

    input must be one of char,short, int

    1
    2
    3
    4
    5
    6
    switch(a):
    {
    case x1: ....; break;
    case x2:....; break;
    default: ....; break
    }

    Pointer and reference

    Pointer Reference
    Pointer is a variable Reference is an essentially implicit pointer or the representation of the address of a memory piece
    Pointer can be empty or uninitialized; Reference requires variable to be initialized before using reference.
  • nullptr

  • virtual pointer

Pointer and Array

  • Array Pointer: the pointer pointing to the address of an array


  • Array Name: array name is not a pointer, but just return the address of the array (address of the first element)


  • Pointer for array element:

    1
    2
    3
    int arr[] = {1,2,3,4,5};
    int *p = arr
    cout<<*p++;
    • *p++ : return element *p, then p++
    • ++*p: (*p) element +1 and then return. Without changing the address pointer p pointing to
  • Array Pointer

    1
    2
    3
    int arr[] = {1,2,3,4,5};
    size =5;
    int (*p)[size] = &arr;
    • (*p)[size] : array pointer, pointing to array NOT element

    • size of (*p)[size] must be number of element in arr

    • p++: address skip the whole array size (5 * 4 bytes
      here), not element size

    • (*p)[0]: return arr[0]


  • Wild Pointer(野指针)
    pointer that has not been initialized before using


  • Dangling Pointer(悬空指针)
    pointer that point to invalid memory address (after memory released)

Macro and Preprocesssor

Difference between Class and Structure

Object-Oriented Design

Basic Features of OOD in C++

  • Three Traits

    1. Encapsulation(封装性)
      A mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user


    2. Polymorphism(多态)
      Different classes inherent from the same parent class can have different methods, class members. It diversifies features of classes. Polymorphims in C++ is achieved by using virtual keyword.


    3. Inheritance(继承)
      The members of the base class become members of the
      derived class. It helps save our time and avoid re-writing the same codes.


  • Publich, Protected, private

    Properties Private Protected Public
    Accessibility only Base Class member/method only Base Class and Child Class member/method Any instance and Class member
    Inheritance Properties:
    • Private Inheritance:
      • Base Class’s private members won’t be inherited by Child Class
      • Base Class’s public and protected members will be converted to be private in Child Class
    • Protected Inheritance:
      • Base Class’s private members won’t be inherited by Child Class
      • Base Class’s protected, public members wil become protected in Child Class,
      • Base Class’s members can not be accessed by Child Class of Base Class’s Child Class.
    • Public Inheritance:
      • Base Class’s private members won’t be inherited by Child Class
      • Base Class’s protected, public members don’t change (Still protected, or public)
  • Types of overloading

    1. overloading the amount of parameter

      Example

      1
      2
      3
      4
      5
      Class A{
      publich:
      void func(int a) {}
      void func(int a, int b) {}
      }
    2. overloading the data types of parameter

      Example

      1
      2
      3
      4
      5
      Class A{
      public:
      void func(int a) {}
      char func(char a) {}
      }
    3. overloading of const and non-const methods

      1
      2
      3
      4
      5
      6
      Class A{
      public:
      void func(int a) {}
      // the const method can not change class member values
      void func(int a) const {}
      }
    4. overloading of Operators

      Example:

      1
      2
      3
      4
      Class A{
      publich:
      int operator + (const int a, const int b) {}
      }
    5. Operators that can not be overloaded:

    • :: , pointer operator . *, condition operator ?: , sizeof, typeof
    • const_cast static_cast dynamic_cast reinterpret_cast
  • Methods that can not be inherent

    1. Constructor
    2. Deconstructor
    3. Friend method
    4. Operators
  • Methods that can be inherited

    1. static functions
    2. non-static functions
    3. non-static members (Note: static members must be private or protected that are usually unable to be inherent)
    4. Virtual function (used for polymorphism)

Interface and Virtual class, method and pointer

  • Pure virtual function
    it is applied by using virtual keyword and =0 behind the function.

    1
    2
    3
    4
    class A{
    public:
    virtual int func(int x) =0;
    }

  • Abstract Class
    Abstract class provide an appropriate base class from which other classes can inherit
    An abstract class must contain at least one pure virtual function


  • Interface
    Interface describes the behavior a class without a particular implementation of that class.
    Interface in C++ is implemented by using Abstract class.


  • Virtual Function and Polymorphism
    A Child of base class can overload the virtual function and give particular implement of the function to achieve polymorphism

  • Virtual Function mechanism: using virtual pointer and virtual table

    1. In base class with virtual function, Compiler creates an virtual pointer vptr and a virtual table vtbl
    2. vptr points to the address of vtbl to write and store the addresses of all virtual functions in this base class.
    3. The pointer vptr is stored at the beginning of the memory of the base class. (the first element of the Class is vptr )
      Example: For class A and Class B, each of them have virtual pointer __vptr__ pointing to a virtual table, which stores addresses of virtual functions. In addition, the virtual pointer of each class is stored at the beginning of the class.
4. In __single inheritance__ (a class is allowed to inherit only one class), child class will inherit the vptr from base class, but __create a new vtbl table to store addresses of new virtual functions and inherited/overrided virtual functions__
5. In __multiple inheritance__: 
    + child class inherits multiple vptr, then creates multiple vtbls, in which each vtbl corresponds to each base class (Hence __the number of vtbl = number of base class inherited__).
    + __All addresses of new virtual functions will be stored at the end of the first vtbls__

Template and Generic Function

  • A generic function defines a general set of operations that will be applied to various types of data.

Memory allocation and Types of memory

  • new and malloc

    new malloc
    A keyword a function
    it calls the operator operator new()
    -> malloc()
    -> then call constructor in class
    directly allocate memory without using constructor
    return class pointer return void pointer
    can be overloading can not be overloading
    No need to tell size of memory Need to tell size of memory
  • delete and free

    delete free
    A keyword a function
    it calls the operator operator delete()
    -> free()
    -> then call deconstructor in class
    directly free memory without using constructor
    return class pointer return void pointer
    can be overloading can not be overloading
    No need to check if memory exists Need to check memory first
  • create and delete Class array

    1
    2
    3
    4
    5
    6
    int size=10;
    ClassA* a = new ClassA[size]
    delete[] a;

    // input is an array of int class
    int ClassA::func(int[] a){....}
  • malloc, calloc, realloc and alloca

    • malloc: allocate memory without initialization

    • calloc: allocate memory and initialize them to zero

    • realloc: extend the memory with bigger size than before.

    • alloca: allocate tempory memory on stack on local scope. Memory will be released outside the scope. Hence no need to use free()

  • Dynamic Link
  • Static Link

Regular Expression (re)

STL container

Reference

[1] https://www.tutorialspoint.com/cplusplus/cpp_overloadinging.htm

[2] https://blog.csdn.net/csdn_chai/article/details/78041050

Comments