panthro
panthro

Reputation: 24061

Global Classes in C++

Im trying to create a global class so I can access it anywhere, but it's not working, I get the error:

a storage class can only be specified for objects and functions

Does anyone know where I'm going wrong?

Here is my h file:

extern class Payments : public QObject
{
Q_OBJECT
public:
    Payments(QObject *parent = 0);
    virtual ~Payments();
    void purchase(const QString &id, const QString &sku, const QString &name, const QString &metadata);
    void getExisting(bool refresh);
    void getPrice(const QString &id, const QString &sku);

public slots:
    void purchaseResponse();
    void existingPurchasesResponse();
    void priceResponse();

signals:
    void purchaseResponseSuccess(const QString &receiptString);
    void existingPurchasesResponseSuccess(const QString &receiptsString);
    void priceResponseSuccess(const QString &price);
    void infoResponseError(int errorCode, const QString &errorText);


private:
    bb::platform::PaymentManager *paymentManager;

};

Upvotes: 2

Views: 5521

Answers (4)

Dietmar Kühl
Dietmar Kühl

Reputation: 153820

For classes the concept of being "global" doesn't really make much sense: Classes are declared wherever they are declared and that's it. Thus, a storage classification isn't allowed when defining a class: You need to remove the extern.

To make the class definition generally available, you need to include its definition in each translation unit where you want to access the class. The way to do this is to put it into a header file and include the file whenever you need the class:

#ifndef INCLUDED_PAYMENTS
#define INCLUDED_PAYMENTS

// headers needed to define Payments

class Payments : public QObject
{
    ...
};

#endif INCLUDED_PAYMENTS

To avoid naming conflicts you should consider declaring your class inside a namespace: The class definitions within a C++ program need to be unique. That is, if another file not including the above header also defines a class Payments in the global namespace but different in some way, these would be conflicting definitions. The compiler isn't required to detect the different uses, however, which may result in hard to diagnose problems.

Upvotes: 1

user405725
user405725

Reputation:

You don't need extern, and it is not even legal in C++ to declare classes as extern. Any class is accessible from anywhere else as long as you don't mess with compiler-specific visibility flags and multiple shared objects (i.e. GCC visibility) and don't create a nested, protected or private class.

Upvotes: 2

Maroun
Maroun

Reputation: 95958

C++ allows the use of the extern only to objects or functions.

Upvotes: 1

jogojapan
jogojapan

Reputation: 69967

The storage-class keyword extern causes the problem. You can't specify this for a class definition. And you don't need it anyway: Your class definition will be accessible from anywhere (provided you #include the file it's defined in).

Upvotes: 3

Related Questions