Initialization List

/**
 * A class for simulating an integer memory cell
 */

class IntCell
{
  public:
    explicit IntCell( int initialValue=0 )
      : storedValue{ initialValue } {} // initialization list
    int read() const
      { return storedValue; }
    void write( int x )
      { storedValue = x; }

  private:
    int storedValue;
};
  • if data members are class types that have complex initializations, using initialization list saves time;
  • if data member is const, the data member's value can only be initialized in the initialization list;
  • the use of braces in C++11 is a part of a larger effort to provide a uniform syntax for initialization everywhere;

explicit Constructor

  • we should make all one-parameter constructors explicit to avoid implicit(e.g. by compiler) type conversions.
IntCell obj; // obj is an IntCell
ojb = 37;    // Should not compile, type mismatch

If not using explicit however, the above can work with implicit type conversion. What the compiler will do is as following,

IntCell temporary = 37;
obj = temporary;

Constant Member Function

accessor: a member function that examines but does not change the state of its object;

mutator: a member function that changes the state;

  • only the const after a closing parenthesis signifies an accessor;
int read() const
  { return storedValue; }

Preprocessor Commands

In order to guard against the danger that an interface might be read twice in the course of compiling a file, each header file uses the preprocessor to define a symbol when the class interface is read.

#ifndef IntCell_H
#define IntCell_H

class IntCell
{
  public:
    explicit IntCell( int initialValue = 0 );
    int read() const;
    void write( int x );

  private:
    int storedValue;
};

#endif

Scope Resolution Operator

The syntax is ClassName::member. The :: is called scope resolution operator.

#include "IntCell.h"

IntCell::IntCell( int initialValue ) : storedValue{ initialValue }
{
}

int IntCell::read() const
{
  return storedValue;
}

void IntCell::write( int x )
{
  storedValue = x;
}

Signatures Must Match Exactly

The member function's signature in class interface and implementation must match exactly.

Objects Are Declared Like Primitive Types

Int C++11, we can write,

IntCell obj1;       // zero parameter constructor
IntCell obj2{ 12 }; // one parameter constructor
IntCell obj3{};     // zero parameter constructor

The declaration of obj3 is nicer because initialization with a zero-parameter constructor is no longer a special syntax case, i.e. the initialization style is uniform.

results matching ""

    No results matching ""