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.

Linux file structure – comparsion with Windows

Here is the Linux file structure from the root, which some explanations. The main explanation for the /bin, /boot /lib are the basic files that are required on boot up that the kernel needs to “run” as such. The files within the /usr are the files that user programs use e.g. games.

Anyway here is a list of directories on my linux setup.

bin binary files for boot up e.g. mount e.g.
boot boot files – kernel images etc.
dev devices on the computer.
etc configuration files for the programs
home home users, e.g. your name /home/ian
lib libraries
lib32 libraries for the 32bit programs
lib64 /lib (link to the libraries since I am using the 64 linux version)
lost+found
media media that is going to be mounted (cd-rom’s)
mnt media that is going to be mounted (Hard drives etc)
opt opitional programs e.g. things like google chrome, they are normally place in here is not distro specific.
proc processes that are happening on the computer, all process you can “talk” to
root root home files.
sbin sbin, booted up at initial stage of the boot process, things like modprobe for setting up systems items.
sys system image of devices attached and also file systems that are loadable.
tmp tempoary files.
usr user files, e.g. games, libraries, binary files
bin games include lib lib32 lib64 local sbin share src
it has its own includes, libraries, sbin and bin directories for all of the files within that user directory.
var variable files, e.g. logs, apache www hosting files.

The Windows equivalent would be that most of the / (root) directory is within the c:/windows directory, apart from the /home which is the c:/Users or c:/Documents depending on your Windows version.

bin /Windows /Windows/System32 /Windows/System
boot boot.ini file that points to what to do.
dev Does not appear to have something similar on the file system
etc /Program Data (depending on Windows versions)
home /Users
lib /Windows /Windows/System32 /Windows/System /Windows/.Net (for .Net stuff) etc.
lib32
media Does not appear to have a link to the different mount points but display them on the windows explorer
mnt Does not appear to have a link to the different mount points but display them on the windows explorer
opt /Program files/
proc Does not appear to have a list of running process on the file system, but you can view them with pslist pskill
root /Documents/Admin user account
sbin /Windows
sys Does not appear to have a list of devices attached
tmp /tmp
usr /Program files/
var /Program files/ or where ever you want them.

That kinder helps me to understand that there is more details on the command line, directory structure to actual processes and devices attached than Windows, well of course there is the regviewer that can display options like the /etc in the linux but nothing as structured, things just across like a mess (to me anyway).

const_cast – cpp

Constant casting (const_cast) is when you have a variable that is declared constant but you want to remove that constant restriction from that variable. In normal C language the (int) casting would suffice, but it may throw up some errors that you really did not want!!.. so using const_cast you can remove the constant restriction with abit more safer feeling as such, and also the const_cast would be upgrade/updated on different versions/compilers etc.

To remove the constant casting the syntax for const_cast is

returnvalue = const_cast<return type>(casting value)

where the returnvalue is the value to be returned from the casting, the return type is what you want the returning value type to be and then the value (casting value) is the actual value (constant value) to be cast.

Here is a another example with abit more code

#include <iostream>
 
using namespace std;
 
int main()
{
  const int pies = 3;
  int &newPies = const_cast<int&>(pies);
  cout << "pies = " << pies << endl;
  newPies += 2;
  cout << "new pies = " << newPies << endl;
 
 // where as you cannot alter the old pies value .. 
 // pies+=2;///error !!
  return 0;
}

and the output would be

pies = 3
new pies = 5

Keeping values a constant is a good thing, but sometimes you want to alter the constant value !!.

As someone said on my similar post on code call

Here is some code to demonstrate how to do something similar to the strstr function, from what “dcs” member said “An example that comes to mind would be writing a function similar to C’s strstr function: the strings passed should not be modified by the function and should therefore be const-qualified. But the returned pointer need not be const, even though it may point to a position in the string which was passed as const-qualified.”

#include <iostream>
#include <string.h>
 
using namespace std;
 
char* codecallStrStr(const char* p1, const char* p2)
{
      bool found;
     // loop through the first string
      while (*p1)
      {
	  // if there is a match between the frist string character and the second string character
	  if (*p2 == *p1)
	  {
	    if (strlen(p2) <= strlen(p1))
	    {
	      found = true;
	      for (int i =0; i < strlen(p2); i++)
	      {
		if (p2[i] != p1[i]) {
		  found = false;
		  break;
		}
	      }
	      if (found) 
	      {
		return const_cast<char*>(p1);
	      }
	    }
	  }
	  p1++;
      }
      return 0;
}
 
int main()
{
    char *searchStr = "hi thre there k ";
    char *pr = codecallStrStr(searchStr, "there");
 
    // check to make sure it was found.
    if (pr)
    {
      cout << pr << endl;
    }
    else
      cout << "no found" << endl;
}

output would be

there k

Reinterpret_cast – cpp

The casting of variables is one way to convert one type of variable to another, for example if you wanted to have Pi being a double number e.g. 3.14 and then wanted to have the integer value instead (just the whole number) then that is a cast of the variable.

The classic was of casting in C language is like

double pi = 3.14;
int piInt = (int)pi;

and the (int) is the casting of one type to another.

But it is better to use the c++ casting techniques, static_cast, const_cast, dynamic_cast and reinterpret_cast. I am going to do a reinterpret_cast, and this is a way of converting a pointer to a variable from one type to another that is not of a similar type and it will try and fit the cast into the return type.

The syntax for reinterpret_cast is

returnvalue = reinterpret_cast<return type*>(casting value);

where the return value is what is casted and the return type is what you want to be casted to, and the casting value is what you want to be casting from.

One good example is how to use the reinterpret_cast is to convert one type into a void pointer (void *) and then back again, it is not really much use in this case and also reinterpret_cast does not do any type checking etc, it will just try and fit the casting value into the return type and if it fits, great, if it does not, great, it really does not care, so that is why it is better to use the static_cast (shall do a tutorial on that next).

#include <iostream>
 
int main()
{
  int *aInt = new int(10);
  cout << "A value = " << *aInt << endl;
 
  void *bVoid = reinterpret_cast<void*>(aInt);
  int *aBack = reinterpret_cast<int*>(bVoid);
 
  cout << "COME BACK TO ME !! A value again = " << *aBack << endl;
}

and the output would be

A value = 10
COME BACK TO ME !! A value again = 10

Since you are playing with pointers to memory locations then if you alter the value of A in that example the returning back cast would also reflect the new value as well.

Here is a example of just that, altering the value within the casted variable and also reinterpret_cast does not matter if you are using standard variable types like int,float etc.. it can also work on classes as well.

#include <iostream>
 
using namespace std;
 
class classA
{
  public:
    int valueX;
    int valueY;
 
    classA() { valueX = 0; valueY = 0;}
 
};
 
int main()
{
  classA *a = new classA();
  a->valueX = 10;
  a->valueY = 30;
  cout << "Value of X = " << a->valueX << " Value of Y = "  << a->valueY << endl;
 
  void *aClassVoid = reinterpret_cast<void*>(a);
 
  a = reinterpret_cast<classA*>(aClassVoid);
 
  cout << "COME BACK To me !! Value of X = " << a->valueX << " Value of Y = "  << a->valueY << endl;
 
  cout << "Value of X = " << a->valueX << " Value of Y = "  << a->valueY << endl;
  aClassVoid = reinterpret_cast<void*>(a);
  // but if you alter the values within a variable once you have done the first cast.
  cout << "After the first cast .. Value of X = " << a->valueX << " Value of Y = "  << a->valueY << endl;
  a->valueX = 0;
  cout << "After settings the value to 0 .. Value of X = " << a->valueX << " Value of Y = "  << a->valueY << endl;
  //and try again with the casting with the aClassVoid
  classA *AP = reinterpret_cast<classA*>(aClassVoid);
 
  cout << "COME BACK To me !! Value of X = " << AP->valueX << " Value of Y = "  << AP->valueY << endl;
 
  cout << "The last reinterpret_cast leaves the value as 0 for valueX because it is still only pointing to the same place as 'a'" << endl;
 
   return 0;
}

and the output is

Value of X = 10 Value of Y = 30
COME BACK To me !! Value of X = 10 Value of Y = 30
Value of X = 10 Value of Y = 30
After the first cast .. Value of X = 10 Value of Y = 30
After settings the value to 0 .. Value of X = 0 Value of Y = 30
COME BACK To me !! Value of X = 0 Value of Y = 30
The last reinterpret_cast leaves the value as 0 for valueX because it is still only pointing to the same place as 'a'

Hope that helps in how to use reinterpret_cast, but as stated before, best to use static_cast because that would give some information if the casting was successful. Also reinterpret_cast can also be used on function pointers to, which is kinder cool. The main reason for reinterpret_cast is that it uses minimal type checking, and if the target as similar bit patterns to the original then we are good to go as such in the reinterpret_cast way of things.

Polymorphism

Polymorphism means that you are deriving from a base class to create a new class, and the polymorphism is when you derive from the base class and implement a interface functions, so that any derived class will have to these functions implement so if you call a function that is defined by the interface to be present, you know it will be implement in some forum.

In php, there is a interface type, so we can define a basic Animal type to print is name, so that any animal that is derived from this interface will have to implement at least the print name function, here is the interface

interface Animal
{
  public function printName();
}

it is very similar to a class structure apart from there is no functional code, just the function definition. To then implement the interface Animal within a class, so that you will know that the printName() function will be implemented you use the “implements” keyword in the class definition as below.

class Cat implements Animal
{....

and then the class Cat will have to define the printName function as

  public function printName()
  {
     echo "Cat class\n";
  }

otherwise if you did not implement it there would be a error on the “compile time” as below.

Fatal error: Class Cat contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Animal::printName)

here is a full code that will do a Cat and Dog class, then you can create a array of different derived Animals interfaces and then just call the printName and you know it will be present.

<?php
interface Animal
{
  public function printName();
}
 
class Cat implements Animal
{
      public function printName()
      {
	echo "Cat class\n";
      }
};
 
class Dog implements Animal 
{
      public function printName()
      {
	echo "Dog class\n";
      }
};
 
$animals = Array(
    new Cat(), new Dog()
    );
 
foreach ($animals as $a)
{
    $a->printName();
}
 
?>

and the output would be

Cat class
Dog class

Polymorphism is great, because you just know that certain functions will be implemented.

Polymorphism

Polymorphism means that you are deriving from a base class to create a new class, and the polymorphism is when you derive from the base class and implement a interface (virtual function in c++ speak as such) functions.

In C++ a virtual function would be

virtual void printName() = 0;

the = 0 means to set the virtual function to point to nothing (pure virtual function).

You could put some code within {} and still call it a virtual function, but that is taking away from the interface idea. (Java,C# and PHP use the interface structures)

In the code below, I have a const string (constant string) and as we know a constant string cannot be altered so to define this string when the constructor is called you place the variable name after the constructor and set it up to the constant value, e.g..

class Shape
{
     const string name;
      // constructor
     Shape(const string& constructorName) : name(constructorName) {};
}

This will setup the constant string when the Shape class has been created on the heap (memory allocation).

To call a parent class, Shape in this instance, constructor you just do something very similar to the setting of the constant string, you place it after the constructor in the subclass and put the parent class that you want to call its constructor after the “:” as

class Rectangle 
{
      Rectangle(const string& constructorName) : Shape(constructorName) {}
}

you can place more code into the {} for the Rectangle constructor still, but the “Shape(constructorName) is calling the parent class “Shape” constructor.

If you do not define the virtual pure function within the derived class, when you try to compile the error would be something similar to

poly.cpp:46: error: cannot allocate an object of abstract type