I’m writing a very simple and small wrapper around sqlite3, and use sqlite3_get_table() to fetch the results as char**. I use a base data class to be able to store the fields in a uniform container, namely record here, and then fetch each data type specifically using derived types.
This is my base class:
class data
{
private:
uint sz;
virtual void abstract() = 0;
public:
inline data(char* pd);
inline data();
uint size() {return sz;}
};
and here’s the sample derived class:
class str : public data
{
private:
string* pdata;
virtual void abstract() {}
public:
inline str(char* pd);
inline operator string();
inline operator const char*();
};
and the record class:
class record
{
private:
ushort cols;
data** entries;
public:
record(char** ppdata, uint col_count);
inline data* operator [](ushort field);
inline uint num_fields() {return cols;}
};
record‘s operator[] (inline data* operator [](ushort field);) allows me to access the base data class this way:
db::str* mys = dynamic_cast<db::str*>((*record)[3]);
and compile: g++ -o main -lsqlite3 main.cpp under Arch Linux, and there’s no problem in compilation. But when I run it I get Segmentation Fault.
Commenting out the dynamic_cast line makes me happy, but I personally guess I’m doing the downcast wrong in someway, rather than thinking there’s a problem with definition or use of the data class.
I also appreciate any radical offenses to my code, since I know I’m a newbie. Thanks so much.
Thank both of you TC1 and Mark Ransom. I tried twiddling my problem and I finally came to realize that this is the best solution, comparing it’s advantages to it’s trade offs, for a simple wrapper like the one I’m writing (sqlite3’s
sqlite3_get_table()):This way I’m making the data* a very suitable pointer type for making a heterogeneous container (Sorry that I didn’t know the word when I asked the question 😉 ) in such a case that data types are limited, 5 in this case, since its working at a somehow low level.
I just used it in my test
mainlike this:And it does give me
3, and certainly its gotta be possible to apply it to any other type too, especially at low level in this case that types are often fundamental rather than say sophisticated inherited ones.I’ve come to believe that in such cases
static_castcan be tolerated, please correct me if I’m wrong. And also I’m really willing to know of both of your criticisms and appreciations about this solution, since it helps me learn more as a beginner.Thank you.