Thinking in C++ Notes (11)

Chapter 11: References & the Copy-Constructor

  • C++中void指针赋值给其他类型指针必须显示转换
  • Reference Rules:
    • must be initialized when it is created
    • Once initialized, it cannot be changed to refer another object
    • You cannot have NULL references
  • when passing argument, const reference is the first choice

Copy-Constructor : Type(const Type&)

  • it is essential to control passing and returning of user-defined types by value during function calls
  • In C and C++, arguments are pushed on the stack from right to left
  • If a function returns large objects, the return address is pushed before making the function call
  • the compiler can create a temporary object whenever it needs one to properly evaluate an expression
  • the compiler will automatically synthesize a copy-constructor if you don’t provide one yourself
  • Memberwise initialization: to create a copy-constructor for a class that uses composition or inheritance, the compiler recursively calls the copy-constructors for all the member objects and base classes
  • Declare a private copy-constructor, pass-by-value is then prevented
  • when you pass the address of an argument to modify, using pointer instead of reference is better for the reader to follow

Pointers to members

int ObjClass::pointerToMember = &ObjClass::a;
ObjClass obj, objp;
poinerToMember = 1;
objp->pointerToMember = 2;

void (ObjClass::
pointerToMemberFunction)(int) = &ObjClass::func;

a pointer-to-member must always be bound to an object when it is dereferenced