Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++
Prev Contents / Index Next

A nested iterator

It’s more common to see a “smart pointer” or “iterator” class nested within the class that it services. The previous example can be rewritten to nest SmartPointer inside ObjContainer like this:

//: C12:NestedSmartPointer.cpp
#include <iostream>
#include <vector>
#include "../require.h"
using namespace std;

class Obj {
  static int i, j;
  void f() { cout << i++ << endl; }
  void g() { cout << j++ << endl; }

// Static member definitions:
int Obj::i = 47;
int Obj::j = 11;

// Container:
class ObjContainer {
  vector<Obj*> a;
  void add(Obj* obj) { a.push_back(obj); }
  class SmartPointer;
  friend class SmartPointer;
  class SmartPointer {
    ObjContainer& oc;
    unsigned int index;
    SmartPointer(ObjContainer& objc) : oc(objc) {
      index = 0;
    // Return value indicates end of list:
    bool operator++() { // Prefix
      if(index >= oc.a.size()) return false;
      if(oc.a[++index] == 0) return false;
      return true;
    bool operator++(int) { // Postfix
      return operator++(); // Use prefix version
    Obj* operator->() const {
      require(oc.a[index] != 0, "Zero value "
        "returned by SmartPointer::operator->()");
      return oc.a[index];
  // Function to produce a smart pointer that 
  // points to the beginning of the ObjContainer:
  SmartPointer begin() { 
    return SmartPointer(*this);

int main() {
  const int sz = 10;
  Obj o[sz];
  ObjContainer oc;
  for(int i = 0; i < sz; i++)
    oc.add(&o[i]); // Fill it up
  ObjContainer::SmartPointer sp = oc.begin();
  do {
    sp->f(); // Pointer dereference operator call
  } while(++sp);
} ///:~

Besides the actual nesting of the class, there are only two differences here. The first is in the declaration of the class so that it can be a friend:

class SmartPointer;
friend SmartPointer;

The compiler must first know that the class exists before it can be told that it’s a friend.

The second difference is in the ObjContainer member function begin( ), which produces a SmartPointer that points to the beginning of the ObjContainer sequence. Although it’s really only a convenience, it’s valuable because it follows part of the form used in the Standard C++ Library.

Thinking in C++
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire