[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppScopeOperator

(C++) Scope operator ::

The operator to get into a scope, being the double colons ::. This scope can be in a namespace or a class.

Function namespace

Here is a code snippet showing how to have the same functions in two different namespaces and how to call them:

  1. include <iostream>
namespace myFirstNamespace { void sayHello() { std::cout << "Hello from myFirstNamespace" << std::endl; } } namespace mySecondNamespace { void sayHello() { std::cout << "Hello from mySecondNamespace" << std::endl; } } int main() { std::cout << "Hello from main" << std::endl; myFirstNamespace::sayHello(); mySecondNamespace::sayHello(); }


Class namespace

  1. include <iostream>
class MyClass { public: static void sayHello() { std::cout << "Hello world" << std::endl; } }; int main() { MyClass::sayHello(); }


The sayHello static member function is a bit of a trivial example (Click here for a better example). More often you use the scope operator when having a derived class calling functions explicitly from its base class:

struct MyBaseClass
{
  virtual void sayHello() const 
  { 
    std::cout << "Hello MyBaseClass" << std::endl; 
  }
};
struct MyDerivedClass : public MyBaseClass
{
  void sayHello() const 
  { 
    std::cout << "Hello MyDerivedClass" << std::endl; 
  }
  void lie() const 
  { 
    MyBaseClass::sayHello(); 
  }
};


last edited (November 16, 2006) by bilderbikkel, Number of views: 7360, Current Rev: 12 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.