Skip to main content
edited tags
Link
Vlad from Moscow
  • 308.8k
  • 27
  • 194
  • 349
Source Link
tuxmania
  • 946
  • 2
  • 10
  • 29

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;
}