0

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
tuxmania
  • 906
  • 2
  • 9
  • 28
  • 1
    Duplicate: http://stackoverflow.com/questions/185844/initializing-private-static-members?rq=1 (taken from the list on the right, seriously!) – Alec Teal Jan 10 '14 at 10:19
  • You could remove the data members and make them local static variables inside `getConnection()`. – juanchopanza Jan 10 '14 at 10:20
  • @AlecTeal it is a duplicate? not really because the answer in your mentioned thread is not applicable since initializing a private static member outside of the class is not possible! – tuxmania Jan 10 '14 at 10:22
  • It really is a duplicate. – Alec Teal Jan 10 '14 at 10:41
  • 1
    to clarify: both are about how to define a private static variable, yes. The problem is a bit different in both cases, but looking at the solution should give the correct idea in any case (here, that the type was missing, there, that the definition was in the header file but should have been in the cpp file). So technically, the question is actually not a real duplicate (it is not the exact same question), but close enough. – codeling Jan 10 '14 at 11:08

1 Answers1

5

Instead of

Connector::conn = 0;

write

sql::Connection * Connector::conn = 0;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • that is the answer i was looking for and it is not mentioned in http://stackoverflow.com/questions/185844/initializing-private-static-members?rq=1 so i don't care if it is a duplicate question, because it certainly is not a duplicate answer. – tuxmania Jan 10 '14 at 10:34