tuxmania
tuxmania

Reputation: 956

initialize private static variable c++

i want to create a Connector class that holds exactly one sql::Connection Pointer. My attempt was to build a singleton Class and make the pointer and constructor itself private. only a static function is public that is allowed to create the connection.

My attempt to use

Connector::conn = 0;

in the implementation module failed since conn is private and not accessable from outside.

If i ommit initiliziation i get an undefined reference error

Connector.h

#ifndef CONNECTOR_H
#define CONNECTOR_H

#include <cppconn/driver.h>
#include <cppconn/exception.h>

class Connector {

public:
    static sql::Connection* getConnection();


protected:
    Connector();
    Connector(const Connector& other) { }

    static sql::Connection * conn;
    static sql::Driver * drive;
};

#endif  /* CONNECTOR_H */

Connector.cpp

#include "Connector.h"

Connector::Connector() {
}

sql::Connection * Connector::getConnection() {
    if(Connector::conn == 0) {
        Connector::drive = get_driver_instance();
        Connector::conn = Connector::drive->connect("tcp://any.de:3306", "any", "any");
        Connector::conn->setSchema("cryptoTool");
    }
    return Connector::conn;
}

Upvotes: 0

Views: 212

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

Instead of

Connector::conn = 0;

write

sql::Connection * Connector::conn = 0;

Upvotes: 5

Related Questions