----------------------------------------------------------------------- C++ Primer for Stupid High Energy Physicists ----------------------------------------------------------------------- (Update Record) 1999/06/05 K.Fujii Original version. ----------------------------------------------------------------------- [0] General Rules ----------------------------------------------------------------------- R1: Declaration of an object allocates NO memory space. One has to define it. R2: When returning a reference, make sure it stays there. R3: When returning a value, make sure it's not a reference. R4: When created with "new", delete it explicitly. R5: Before you do it, make sure that the pointer is nonzero. R6: When overriding a function of a super class, make sure you override it entirely: watch out overloaded functions. ----------------------------------------------------------------------- [1] How to compose classes that require some argument(s) to construct ----------------------------------------------------------------------- Use a member initialization list: class Composed { private: Component1 fC1; // 1st component class ... public: Composed() : fC1(some_argument....), .. {} ..... }; (e.g.) class LVector { private: TVector fP; // declaration w/o allocation public: LVector() : fP(4) {}; // this allocates a TVector of size 4 .... }; ----------------------------------------------------------------------- [2] How to use a static data member ----------------------------------------------------------------------- Declare it in a class header (A.h): class A { public: static const B kB; static const Int_t kI; static const Char_t *kS; static Int_t gI; .... }; Define it ONCE in its implementation (A.cxx) w/o the "static" key word: const B A::kB(....); // instantiate kB const Int_t A::kI = 0; // can be A::kI(0) const Char_t A::kS = "Some string"; // instantiate a string const Int_t A::gI = 0; // like A::kI .... A::A() { ..... } ----------------------------------------------------------------------- [3] How to declare a global binary operator ----------------------------------------------------------------------- Use a friend function: class A { public: friend A operator + (const A& a1, const A& a2); ... }; You can do a similar thing for unary operators: class A { public: friend A operator - (const A& a1); ... };