Tuesday, November 2, 2010

Using Directives

The following code does not compile:

    namespace A {
       int a = 5;
       namespace B {
          int b = a;
       }
    }
    using namespace A::B;
    int c = a;
    int main() {return c;}

Because a is not in the A::B namespace. This is trying to show that just because you are using an inner namespace, it does not mean you get to see the outer one.

Using Declarations

The following code compiles:

  struct A {
    static const int a = 5;
    struct B {
      static const int b = a;
    };
  };
  int c = A::B::b;
  int main()
  {
    return c;
  }

Using Declarations

The following code does not compile:

  namespace A {
    static const int a = 5;
    namespace B {
      static const int b = a;
    }
  }
  using A::b;
  int c = b;
  int main()
  {
    return c;
  }

Because b is not in namespace a. If the using declaration was 'using A::B::b' then it would compile.

Monday, November 1, 2010

Abstract Class

An abstract class has at least one pure virtual function.

PIMPL Idiom

When refactoring a class so that it uses the pimpl (pointer to implementation) idiom, it does not make sense to put the protected members in the pimpl class.

Protected members are meant to be used by derived classes. You cannot get to the protected members if they are in the Impl class to derive from.

Reference: Exceptional C++ by Herb Sutter. Addison-Wesley, 1999, p. 110.

C++ Style Structs

The following code is in the C style and not in the C++ style:

typedef struct MyStruct_tag
{
  int a;
  int b;
} MyStruct;

The following code is in the C++ Style:

struct MyStruct
{
  int a;
  int b;
};
The following program compiles:

#include <iostream>
using namespace std;
int main() {
  cout << '"' << endl;
  return 0;
}

This code streams out the " character. Sometimes when you want to quote something, this looks nicer than "\"".

Note that streaming """", """""", or any other even number of double quotes streams nothing because "" next to "" concatenates the empty string with the empty string.