Aquarius_Girl
Aquarius_Girl

Reputation: 22906

error: expected unqualified-id before ‘.’ token

class A
{
    private:
        A () {}

    public:
        static A* getInstance ()
        {
            return new A ();
        }
};

int main ()
{
    A.getInstance ();
    return 0;
}

results in the error stated in the title. I do realize that if I create a variable in class A and instanciate it there and return it directly, the error will vanish.

But, here I want to understand what is the meaning of this error and why can't I use it this way.

Upvotes: 3

Views: 36677

Answers (5)

user1360764
user1360764

Reputation:

getInstance is a static function of class A. The right form of calling a static function of a class is <class_name>::<static_function_name>.

We can also call the static function by creating object of the class and using . operator: <class_object>.<static_function_name>

Upvotes: 2

hmjd
hmjd

Reputation: 121961

Use scope resolution operator :: (not . like in Java for example):

A::getInstance();

Upvotes: 3

Hemant Metalia
Hemant Metalia

Reputation: 30638

use scope Resolution Operator ::

e.g.

class::methodName()

Upvotes: 1

dirkgently
dirkgently

Reputation: 111120

You can call a static member function using either . or ::. However, if you use class name you need to use the latter and an object then use the former.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258558

You need to call the method using the scope resolution operator - :::

 A::getInstance ();

Also, if this is meant to be a singleton, it's a very bad one. Whenever you call getInstance(), you'll receive a new object, and you'll run into memory leaks if you forget to delete any instances.

A singleton is usually implemented like so:

class A
{
    private:
        A () {}
        static A* instance;
    public:
        static A* getInstance ()
        {
            if ( !instance )
                instance = new A ();
            return instance;
        }
};

//implementation file
A* A::instance = NULL;

Upvotes: 12

Related Questions