Monday, March 2, 2009

C++ survival kit

  • If you don't want somebody to instanciate your class, set the constructor private

  • Operator precedence
    http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

  • Operator overloading:
    Complex Complex::operator+( Complex &other ) {
    return Complex( re + other.re, im + other.im );
    }
    


  • Dummy template
    // ---------------------------------------
    class MyPairClass
    {
    int pair_1;
    int pair_2;
    };
    
    // ---------------------------------------
    template < class T, int i > class MyTemplate
    {
    public:
    T* testFunc(T* pl);
    };
    
    template < class T, int i >
    T* MyTemplate::testFunc(T* p1) 
    {
    return p1;
    };
    
    // ---------------------------------------
    void myTemplateFunc()
    {
    
    MyPairClass * myPairClass = new MyPairClass();
    MyTemplate < MyPairClass, 2 >  myList;
    myList.testFunc(myPairClass);
    }
    


  • Access to class members
    The default access to class members (members of a class type declared using the class keyword) is private; the default access to global struct and union members is public. For either case, the current access level can be changed using the public, private, or protected keyword.

  • const array size
    const int maxarray = 255;
    char store_char[maxarray];  // allowed in C++; not allowed in C
    
  • No comments: