Dot "." or qualify "::" operator?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Johs

    Dot "." or qualify "::" operator?

    When I declare a string in C++ I type:

    std::string mystring = "sdfsdf";

    afterwards I can access string methods like:

    mystring.

    but why is there both :: and . operators and what are the difference?
  • Colander

    #2
    Re: Dot ".&quot ; or qualify "::&quo t; operator?

    On Apr 22, 7:03 pm, Johs <a...@asd.comwr ote:
    When I declare a string in C++ I type:
    >
    std::string mystring = "sdfsdf";
    >
    afterwards I can access string methods like:
    >
    mystring.
    >
    but why is there both :: and . operators and what are the difference?
    :: works on types/namespaces, . works on instances.

    std is a namespace, so you use ::
    mystring is a variable, so you use .

    Class A
    {
    public:
    static int b;
    }


    // A is an type
    A::b;

    or

    // a is an variable
    A a;
    a.b;

    Comment

    • Rolf Magnus

      #3
      Re: Dot &quot;.&quot ; or qualify &quot;::&quo t; operator?

      Johs wrote:
      When I declare a string in C++ I type:
      >
      std::string mystring = "sdfsdf";
      >
      afterwards I can access string methods like:
      >
      mystring.
      >
      but why is there both :: and . operators and what are the difference?
      The former is used for classes and namespaces, the latter for objects.

      Comment

      • Ron AF Greve

        #4
        Re: Dot &quot;.&quot ; or qualify &quot;::&quo t; operator?

        Hi,

        In addition to the previous answers. If you have for instance a class with a
        static function (i.e. independent of a specific object (the 'this' pointer
        is not passed)) you could use ::

        class example
        {
        public:
        static void StaticFunction( )
        {
        }
        void ObjectFunction( )
        {
        }
        };


        .......
        #include <memory>
        using namespace std;
        ....

        example::Static Function(); // this is ok, no object (this pointer) available
        or needed)

        auto_ptr<exampl eEx( new example);
        Ex->ObjectFunction (); // this too, we need a real object here, the this
        pointer is needed (invisible, pushed last on the stack)


        Regards, Ron AF Greve



        "Rolf Magnus" <ramagnus@t-online.dewrote in message
        news:f0g5j6$8vu $01$1@news.t-online.com...
        Johs wrote:
        >
        >When I declare a string in C++ I type:
        >>
        >std::string mystring = "sdfsdf";
        >>
        >afterwards I can access string methods like:
        >>
        >mystring.
        >>
        >but why is there both :: and . operators and what are the difference?
        >
        The former is used for classes and namespaces, the latter for objects.
        >

        Comment

        Working...