Namespace_mechanism Namespace_mechanism

Namespace mechanism - Definition and Overview

A namespace, in the context of computer programming, refers to the concept of the name of a construct, variable or constant, and within which scopes it is visible.

Example:

class Chicken () : public Bird {
  public:
    int   nWings = 2;
    int   nLegs = 2;
    int   bFlight = FALSE;
    void  Cluck () {}
}

class Hen () : public Chicken {
  public:
    void  LayEggs () {}
}

class Cock () : public Chicken {
  public:
    void  Cockadoodledoo () {}
}

void main () {
    Chicken* pClucker;   // Chicken pointers can be used with Chickens, Hens and Cocks
    pClucker = new Hen;  // create a Hen

// The functions Cockadoodledoo (), Cluck (), and LayEggs () are not available at this scope.  
// They are within a different namespace.

    Cluck ();    // This function call will fail, there is no Cluck () in this namespace.
    LayEggs ();  // This function call will fail, there is no LayEggs () in this namespace.

// These function calls will succeed, because they are being called within a different namespace.

    pClucker -> Cluck ();    // you can call a Chicken function through a Chicken pointer
    pClucker -> LayEggs ();  // you can call a Hen function through a Chicken pointer

// If we define Cluck () outside the context of a Chicken...

    void Cluck () {}

// ...this function call will now succeed.

    Cluck ();

// Note that these two function calls...

    pClucker -> Cluck ();    
    Cluck ();

// Now do two different things, because they are being called from different namespaces; 
// the Chicken namespace, and the main () namespace.

}

(This example may have confused the concept of "scope" with the concept of "namespace". Please adjust accordingly.)

Copyright 2009 WordIQ.com - Privacy Policy  :: Terms of Use  :: Contact Us  :: About Us
This article is licensed under the GNU Free Documentation License. It uses material from the this Wikipedia article.