Session 3/7

notes

Initialisation lists

Initialisation list are a list of initialised attributes, or calls for Base classes constructors that can appear solely in the constructor. This feature was introduced to the language to enforce the rule that when the constructor code is executing all the classes dependencies are already set/constructed 

class Base {
   public:
   Base(int i) { ... }
  
};

class Derived : public Base {
  public:
    Derived(string& str): Base(4), myPi(3.14), refToString(str) { someInt = 1; }     

  private:
    const double myPi;        // Must be initialised in initialisation list (->const)
    string&      refToString; // Must be initialised in initialisation list (->reference)
    int          someInt;     // Can be initialised inside the Constructor code scope
};

Items that must be in initialisation list

  1. Base classes
  2. const attributes
  3. reference attributes

Any user data type (class) will also benefit from being initialised in the initialisation list, and most programmer just prefer to do all initialisation there.

 

C FILE vs C++ fstream

There is not much that can be argued for or against C FILE vs fstream, The only main advantage is the fact that the fstream is exception safe, while FILE is exception agnostic. 

It could also be argued that fstream can be used in a polymorphic manner (being a type of stream)

// Opening and reading using fstream
std::fstream fstr(fileName, std::ifstream::binary | std::ifstream::in)
fstr.read(buffer, length)
fstr.close()

// Opening and reading using FILE
FILE *file = fopen(fileName, "rb");
fread(buffer, length, 1, file);
fclose(file);

Note that in both examples above

- fileName is the name of the file (Fullpath or relative path) 

- buffer is at least of size length bytes

- length is an integer, number of bytes to read

Made with Slides.com