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;
}
5
  • 1
    Duplicate: stackoverflow.com/questions/185844/… (taken from the list on the right, seriously!)
    – Alec Teal
    Commented Jan 10, 2014 at 10:19
  • You could remove the data members and make them local static variables inside getConnection(). Commented Jan 10, 2014 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
    Commented Jan 10, 2014 at 10:22
  • It really is a duplicate.
    – Alec Teal
    Commented Jan 10, 2014 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
    Commented Jan 10, 2014 at 11:08

1 Answer 1

5

Instead of

Connector::conn = 0;

write

sql::Connection * Connector::conn = 0;
1
  • that is the answer i was looking for and it is not mentioned in stackoverflow.com/questions/185844/… so i don't care if it is a duplicate question, because it certainly is not a duplicate answer.
    – tuxmania
    Commented Jan 10, 2014 at 10:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.