struct – what are they for

A struct (structure) is a defined type that the user can define at compile time, for example if you want to have a user defined type that holds details of a database connection you could hold the hostname, username, password of the database connection within a structure (struct) without having to define 3 different variables you only have one that you need to fill in.

For the above example of a database struct

struct database_connection
{
   char *username;
   char *hostname;
   char *password;
};

then within the code you could create a new structure of this type and also fill in the details as

database_connection mydatabase;
mydatabase.username = "usernamebob";
mydatabase.hostname = "localhost";
mydatabase.password = "userpassword";

and you just need to pass that struct to a function if you wanted to to do the connections e.g.

bool dummyconnection(database_connection conn)
{
   createdatabase( conn.hostname, conn.username, conn.password);
}

saves passing in three different parameters.

typedef – what are they for

The typedef is to shorten the naming of some types e.g. is you want to have short unsigned called SHORTUN for quicker typing you can use the type definition syntax of

typedef <old type> <new type>

so regarding the example of short unsigned to SHORTUN

typedef short unsigned SHORTUN

a probably better example would be if you wanted to have a apple as a type (which would be a integer value) then you could

typedef in APPLE

now you could use the code

APPLE apple = 1;

mysql – connection example

Mysql is a database, and to gain access to the data within C++ you will need to be able to “talk” to the database via queries (just like on the mysql command line interface e.g. select * from tablename), the connection process is very similar to the command line interface you will need to supply connection details as in hostname (localhost normally), username, password, database to use and also there are other details that you can pass e.g port number more information can be gained from the MYSQL API pages

To start with I created a struct that will hold the username, host etc details.

struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};

In essence to connect to a database I have created a function that will connect and return a MYSQL pointer to the new connection using the structure above connection_details.

MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
     // first of all create a mysql instance and initialize the variables within
    MYSQL *connection = mysql_init(NULL);
 
    // connect to the database with the details attached.
    if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)) {
      printf("Conection error : %s\n", mysql_error(connection));
      exit(1);
    }
    return connection;
}

That is it, you are connected now, now you can perform some sql queries, once again I have created a function to accomplish this and it returns a MYSQL_RES (mysql result pointer)

MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
   // send the query to the database
   if (mysql_query(connection, sql_query))
   {
      printf("MySQL query error : %s\n", mysql_error(connection));
      exit(1);
   }
 
   return mysql_use_result(connection);
}

since you are now connected and also preformed a query, lets say the query was

SHOW TABLES;

You can traverse the results with a while loop in C++ and use the mysql_fetch_row function from within the mysql library set where a row is a type of MYSQL_ROW.

MYSQL_ROW row;
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("%s\n", row[0]);

Here is the full code that will display all of the tables within the mysql database database, you will need to alter the username and password for the mysql access details.

#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
 
// just going to input the general details and not the port numbers
struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};
 
MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
     // first of all create a mysql instance and initialize the variables within
    MYSQL *connection = mysql_init(NULL);
 
    // connect to the database with the details attached.
    if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)) {
      printf("Conection error : %s\n", mysql_error(connection));
      exit(1);
    }
    return connection;
}
 
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
   // send the query to the database
   if (mysql_query(connection, sql_query))
   {
      printf("MySQL query error : %s\n", mysql_error(connection));
      exit(1);
   }
 
   return mysql_use_result(connection);
}
 
int main()
{
  MYSQL *conn;		// the connection
  MYSQL_RES *res;	// the results
  MYSQL_ROW row;	// the results row (line by line)
 
  struct connection_details mysqlD;
  mysqlD.server = "localhost";  // where the mysql database is
  mysqlD.user = "mysqlusername";		// the root user of mysql	
  mysqlD.password = "mysqlpassword"; // the password of the root user in mysql
  mysqlD.database = "mysql";	// the databse to pick
 
  // connect to the mysql database
  conn = mysql_connection_setup(mysqlD);
 
  // assign the results return to the MYSQL_RES pointer
  res = mysql_perform_query(conn, "show tables");
 
  printf("MySQL Tables in mysql database:\n");
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("%s\n", row[0]);
 
  /* clean up the database result set */
  mysql_free_result(res);
  /* clean up the database link */
  mysql_close(conn);
 
  return 0;
}

To compile up this program you will need to link to the mysql libraries and headers that are used within the program, e.g. mysql.h at the top of the program. To gain access to these, there is a nice mysql_config (you may need to install it via your package manager system if you do not have it already).

Here are my outputs of what is required on the command line for the g++ compiler

mysql_config --cflags
-I/usr/include/mysql  -DBIG_JOINS=1  -fno-strict-aliasing   -DUNIV_LINUX
mysql_config --libs
-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqlclient

These are the g++/c++ switches that tell the compiler where the libraries (-L) are and the headers (-I) and to insert into the g++/c++ compiler line within linux you can do something like

g++ -o mysqlconnect $(mysql_config --cflags) mysqlconnect.cpp $(mysql_config --libs)

Where the mysqlconnect.cpp is the c++ file of the above program and the output would be

./mysqlconnect
MySQL Tables in mysql database:
columns_priv
db
event
func
general_log
help_category
help_keyword
help_relation
help_topic
host
ndb_binlog_index
plugin
proc
procs_priv
servers
slow_log
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_transition
time_zone_transition_type
user

Method adding two numbers

Method programming with C++ is a way to save time when you need to redo same/similar code, and also it allows for clearer code because when you read the code you can tell what is happening instead of just having the same code over and over again within the main method of the program.

To declare a method within c++ there is syntax for the way that a method is defined.

[return type] methodname(parameters if required...)

So for example if you want to pass in two integer variables and then to return a integer variable (the function could add the parameters together so shall we call it addTwoNumbers,

int addTwoNumbers(int value1, int value2);

this means that the return value is a int (integer), you “call” the method by its name (addTwoNumbers) and pass in local variables to the method in the parameters (value1 and value2).

Here is a full c++ code example that will read in two values from the keyboard and output the result to the screen.

#include <iostream>
#include <exception>
#include <stdio.h>
 
//using the namespace std (standard) for the cin -> console input
using namespace std;       
 
int addTwoNumbers(int val1, int val2)
{
    return (val1 + val2);
}
 
int main()
{
       // setup the defaul values.
       int val1 =0, val2 =0;
       try 
       {
              // output to the console
              printf("Please enter number 1 : ");
              // read in the input, if not a integer value, this will
              // cause a error 
              cin >> val1;       
              printf("Please enter number 2 : ");
              cin >> val2;
       }
       catch (exception& e)
       {
              // write out any error exception
              printf("Not a valid input %s\n", e.what());
       }
       // output the answer of the two inputted values.
       printf("Answer : %d\n", addTwoNumbers(val1, val2));
       return 0;
}

and here is the output

Please enter number 1 : 20
Please enter number 2 : 10
Answer : 30

Library of your own – object file.

Sometimes you want to have a library of your functions within one object file that you can use for other applications without having to re-compile and import each time to each project.

Well, if you create a object of the list of functions because a object file is the intermediate between code and linking (to create the executable file), but with this object file you will need to have created a header file (.h) that will allow the projects to know what functions are within the object file and how to call them. So to start with here is the header file (I have called it libraryHelloWorld.h)

#include <iostream>
 
using namespace std;
 
void SayHelloWorld();
void SayWord(std::string st);

It just defines the two functions that I have written, and here are the implementation of the two functions above.

#include "libraryHelloWorld.h"
#include <iostream>
 
using namespace std;
 
void SayHelloWorld()
{
    cout << "Hello World" << endl;
}
 
void SayWord(string st)
{
    cout << "Line is \"" << st << "\"" << endl;
}

if you save that as libraryHelloWorld.cpp, if you notice that at the top I am including the header file to this cpp file because the header files normally have a class definition inside them and also struct’s etc, which the functions within the cpp file may require.

To compile up, to create the object file you just need to do

g++ libraryHelloWorld.cpp -c

which basically means (-c) just compile and do not link, this will create a libraryHelloWorld.o file (the object file).

To make use of this object file, you just need to add in the header file to your project and then call the functions as though you have re-written them within your new project, like so.

#include "libraryHelloWorld.h"
 
int main()
{
  SayHelloWorld();
  SayWord("Genux is great");
  return 0;
}

Then the main part, which is including the object file created before into the linking part of the computation of this program. (save the above as callHelloWorld.cpp)

g++ callHelloWorld.cpp libraryHelloWorld.o -o callHelloWorld

the above includes the object file, libraryHelloWorld and after the linking part of the compilers job, the output file name (-o) will be callHelloWorld.

This just saves allot of time when you are coding, try to keep different projects having similar libraries that you know and trust to work.

dynamic_cast – cpp

The casting of variables, is when you change one type of variable to another, for example to change a integer value to a double value. But when it comes to classes, casting is allot more fun. Because since a casting variable has to be compatible with the return casting type, the base class will need to be polymorphic for this to work (virtual functions within the base class).

The basis of a dynamic_cast syntax is as follows.

return variable = dynamic_cast<return type>(casting value)

To try and demonstrate how dynamic_cast(ing) works here is a example code broken down into chunks. Here is the base class, that has the virtual int returnX() method.

class baseClassDoesWork
{
  protected : 
     int x;
  public : 
     baseClassDoesWork()  { x = 55; };
     virtual int returnX() { cout << "Base class" << endl; return x;}
     void setX(int newXValue) { x = newXValue;}
};

and here is the sub class that will inherit the base class and re-do the virtual method

class subBaseClassDoesWork : public baseClassDoesWork
{
  public : 
      subBaseClassDoesWork() : baseClassDoesWork() {};
      int returnX() { cout << "Subclass" << endl; return x;}
};

here, there is no real difference between the two functions, because the demo is about how dynamic casting works, but I have added in some debugging code to say what class is being called.

Since a dynamic_cast will cast the virtual functions, then the polymorphism effects the casting and newer virtual function that is in the subclass still will call called. But the casting to the class other functions will not “follow” the cast. In the example below first we are creating a subclass and then creating a base class from a dynamic_cast of the subclass (as stated before the base class casting will still include the virtual function from the subclass), so that if you want to convert to another class that also inherited from the base class but not the subclass then you can now convert to the new class.

Here is the code.

#include <iostream>
 
using namespace std;
 
class baseClassDoesWork
{
  protected : 
     int x;
  public : 
     baseClassDoesWork()  { x = 55; };
     virtual int returnX() { cout << "Base class" << endl; return x;}
     void setX(int newXValue) { x = newXValue;}
};
 
class subBaseClassDoesWork : public baseClassDoesWork
{
  public : 
      subBaseClassDoesWork() : baseClassDoesWork() {};
      int returnX() { cout << "Subclass" << endl; return x;}
};
 
int main()
{
    // this one does work because of the virtual method in the base class.
    // but we can create a sub class of the base class first.
    subBaseClassDoesWork *subBase = new subBaseClassDoesWork();
    // convert it to the base class
    baseClassDoesWork *baseDoes = dynamic_cast<baseClassDoesWork*>(subBase);
 
    // check to see if the casting worked e.g. not equal to 0
    if (baseDoes == 0)
      cout << "Bad casting" << endl;
    else
      cout << baseDoes->returnX() << endl;
 
    // re-set the value of X
    baseDoes->setX(30);
 
    // convert it back again to the sub class and things are still great :).
    subBaseClassDoesWork *subBase2 = dynamic_cast<subBaseClassDoesWork*>(baseDoes);
    if (subBase2 == 0)
      cout << "Bad casting" << endl;
    else
      cout << subBase2->returnX() << endl;
 
    return 0;
}

The output would be

Subclass
55
Subclass
30

Where as this would not work because there is no virtual functions to really link the classes together (polymorphic), error included in the source where the error would be.

#include 

using namespace std;

class baseClassNotWork
{
protected :
int x;
public :
baseClassNotWork() { x = 0; };
int returnX() { return x;}
};

class subBaseClassNotWork : public baseClassNotWork
{
public :
subBaseClassNotWork() : baseClassNotWork() {};
int returnX() { return x;}
};

int main()
{
baseClassNotWork *baseNot = new baseClassNotWork();
//error: cannot dynamic_cast

Static_cast – cpp

Static casting (static_cast) is when you want to change the type of the variable e.g. if you want to have a the number of pies that are left to be 0.5 instead of a whole value then you would need to change the integer value to a double. The static_cast can change one type to another, as long as it is compatible.

The general syntax for static_cast is

returnvalue = static_cast<returntype>(value to cast)

Where the return value is the value returned from the casting, returntype is the variable type that you want to have (e.g. double) and the value to cast speaks for itself.

For the example above about pies, the code would be

     int pie = 3;
     double fl = static_cast<double>(pie);

The static_cast(ing) and also other types of casting are the long form as such compared to the standard C version of

   double fl = (double)pie;

But with the static_cast you can be sure that the implementation will be type checked and also because of the classes etc then you need to type check the results unless you may have some value that is not want you was wanting.