Babra Cunningham
Babra Cunningham

Reputation: 2967

Peculiar behavior of nested class pointers?

I'm using mysql-conntector++ and I'm interested by some of the behaviors of the pointer types such as:

sql::Driver *driver__; 

or

sql::Connection *connection__;

Clearly ::Driver and ::Connection are nested classes of sql, when I attempt to initialise either of these pointers on the heap:

sql::Driver *driver__ {new sql::Driver()};

Error:

error: invalid new-expression of abstract class type ‘sql::Driver’
    sql::Driver *driver__ {new sql::Driver()};

How do libraries implement this type of behavior with nested classes and pointers to such classes?

I've looked over the mysql-connector++ source code and can't seem to identify the relevant section.

N.B the above errors have been produced using CMake with -std=c++14

Upvotes: 0

Views: 56

Answers (2)

Jeandey Boris
Jeandey Boris

Reputation: 743

In fact, when you declare

sql::Driver *driver__;
sql::Connection *connection__;

you declare references to instances which implement interfaces of:

  • a SQL driver
  • a SQL connection

In order to instanciate such instances, the library provides you factories in this way

driver__ = get_driver_instance();
connection__ = driver->connect("tcp://127.0.0.1:3306", "root", "root");

Once instanciated, you'll manipulate only the public interfaces of such instances.

Upvotes: 0

eerorika
eerorika

Reputation: 238361

How do libraries implement this type of behavior with nested classes and pointers to such classes?

Concrete instances of abstract classes only exist as a base class sub-object. The way to make those is inheritance:

struct MyDriver : sql::Driver {
    //TODO implement all pure virtual functions of sql::Driver
}

// imaginary implementation
Driver* get_driver_instance() {
    static MyDriver instance;
    return &instance;
}

PS. The fact that Driver is a member of sql (namespace?) is not significant to the user in other way, except the way it affects name lookup.

Upvotes: 3

Related Questions