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

J

Johs

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?
 
C

Colander

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;
 
R

Rolf Magnus

Johs said:
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.
 
R

Ron AF Greve

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::StaticFunction(); // this is ok, no object (this pointer) available
or needed)

auto_ptr<example> Ex( 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

http://www.InformationSuperHighway.eu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top