11/1/2018 - 2:49 PM

C++ class

class MISC


  • By providing a constructor requiring parameters,
    • No default constructor will be generated by the compiler for that class
    • No default constructor will be available to create objects of that class
  • It is always not bad to use explicit before a single parameter constructor


  • Remember to release memory if the member data includes a pointer, because default decoonstructor will only delete the poiner, but not the memory it refers to.

Static Member

  • In BLP, use "s_datamembername".
  • It's shared among all instances of that class.
  • It can also be accessed without an object as ClassName::s_member
  • Static methods are methods that do not require an object to be instantiated. However this means they can only access other static methods and data members
  • In general, methods that never require any data from an object should be made static
  • Constants inside a class should be made static to save space

Constant Static Data member:

  • can be declared as: static const T s_data
  • It can be initiated once, so it is usually initiated in a .cpp file

Static Function member:

  • A Static function can not be const
    • 因为在底层的实现中,static function的args中没有this,所以没法使得this变const.

Operater overloading

It's best to make it a non-member non-friend function, use accessor to get the data. Which means it should be defined out of the class definition. E.g.

Class A{
  bool operator < (){}


bool operator<(const Account& lhs, const Account& rhs) {
 return lhs.balance() < rhs.balance(); // compare accounts by balance

Friend class/function


#include <iostream> 
class A { 
    int a; 
    A() { a=0; } 
    friend class B;     // Friend Class 
class B { 
    int b; 
    void showA(A& x) { 
        // Since B is friend of A, it can access 
        // private members of A 
        std::cout << "A::a=" << x.a; 
int main() { 
   A a; 
   B b; 
   return 0; 
  • Friend is not mutual.
  • Friendship is not inherited

Enum defined in class

Use ClassName::EnumName to access it from outside, remember to make it public.

Template Function


template <typename T>
void swap(T& x, T& y) 
    T xCopy(x);
    x = y;
    y = xCopy;

Pros & Cons:

  1. The compiler need to check dependencies during compiling.
  2. Template function can be overloaded by other template function or non-template function
  3. 在没有被feed T的时候,compiler会做type deduction,但是不会做type conversion, 因为会导致歧义
  4. Template members are typically defined in header files, whether or not they are inline (why?)