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 

Hello World

Flex is the Flash SDK from Adobe, you can download a open source command line compiler from adobe (Flex open source page ). The Free SDK link is here.

Once you have downloaded the free SDK, you will need to place into the system. I have placed mine into /opt directory called flex_sdk_3, so something like (you will need to be root to do this!)

cd /opt
mkdir flex_sdk_3
cd flex_sdk_3
unzip <place where your free sdk is)

and then create a place for where you are going to be creating your flex scripts, I placed mine into my home directory under my programming/flex sturcture, so this is where I am

mkdir -p ~/Programming/flex/

The -p will create any directories that are not present there already, and also the ~ is for the home directory that user.

I then copied the flex-config.xml from the /opt/flex_sdk_3/frameworks directory into the Programming/flex directory and edited it to the new values.
The full differences between the standard flex-config.xml and the one that I have altered is below, but basically I have added into the xml elements values the new directory for where flex-sdk is (e.g. /opt/flex_sdk_3/) so that flex’s command line environment will know where to get the libraries to compile and create the swf (ShockWave Flash), but here are the elements that I have altered.

<external-library-path>
     <path-element>/opt/flex_sdk_3/frameworks 
<library-path>
     all the <path-element's>/opt/flex_sdk_3/frameworks
<namespaces>
   the <manifest>/opt/flex_sdk_3/frameworks path to the framework directory file.

Because the class structure follows the directory structure of the directories below the compiling environment, I created the following directory structure com/codingfriends/helloworld with

mkdir -p com/codingfriends/helloworld

which will create the whole structure if there is no directories there already.

Then you can place these two files into the helloworld directory

This is the class Greeter that is created and turned into a object within the swf file save this as Greeter.as

// the directory structure of where the class is.
package com.codingfriends.helloworld
{
	public class Greeter
	{
		private var name:String;
 
		// constructor
		public function Greeter(initialName:String="Ian")
		{
			name = initialName;
		}
 
		// sayHello returns a String
		public function sayHello():String
		{
			var result:String;
			// if the class private name is present
			if (name!=null && name.length >0)	
			{
				result = "Hello there, "+name+".";
			}
			// should never reach here on a basic run.
			else 
			{
				result="Hello there.";
			}
 
			return result;
		}
	}
}

var = variable and the type of variable or return variable is at the end of the definition e.g.

public var name:String; // this is a variable named "name" and it is of type String
public function sayHello():String // this is a function named "sayHello" and returns a String type

save this as Greeter_mx.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="initApp();">
<mx:Script>
<![CDATA[
import com.codingfriends.helloworld.Greeter;
// the initialize application .. the start
private function initApp():void
{
	// create a new Greeter object with no passing in name
	var myGreeter:Greeter = new Greeter();
	// and say hello world 
	output.text+=myGreeter.sayHello();
	// create a new greeter with the name = genux instead
	var newGreeter:Greeter = new Greeter("genux");
	output.text+=newGreeter.sayHello();
}
]]>
</mx:Script>
 
<mx:Text id="output" width="100%" textAlign="center"/>
</mx:Application>

The is the place where the code starts, the rest is just the adobe application settings, within the code there is a reference to “output”, which is defined in the

PATH=$PATH:/opt/flex_sdk_3/bin

and then to compile up the source code

mxmlc -load-config flex-config.xml -source-path=~/Programming/flex/actionscript/ ./com/codingfriends/helloworld/Greeter_mx.mxml -output ./bin/Greeter_mx.swf

the -load-config will load the one in the present directory which I altered, and -source-path is there so that the base directory is used for compiling so the compiler will know where to get the com/codingfriends/helloworld/Greeter.as and Greeter_mx.mxml, and the -output is what the output flash file is/placed.

Here is the output of the Greeter.swf file.


Here is the difference (diff) between the flex-config.xml from the one that I edited and the one that was in the /opt/flex_sdk_3/frameworks directory.

53c53
<           <path-element>/opt/flex_sdk_3/frameworks/libs/player/{targetPlayerMajorVersion}/playerglobal.swc</path-element>
---
>           <path-element>libs/player/{targetPlayerMajorVersion}/playerglobal.swc</path-element>
70c70
<          <path-element>/opt/flex_sdk_3/frameworks/libs</path-element>
---
>          <path-element>libs</path-element>
72,74c72,74
<          <path-element>/opt/flex_sdk_3/frameworks/libs/player</path-element>
<          <path-element>/opt/flex_sdk_3/frameworks/libs/player/{targetPlayerMajorVersion}</path-element>
<            <path-element>/opt/flex_sdk_3/frameworks/locale/{locale}</path-element>
---
>          <path-element>libs/player</path-element>
>          <path-element>libs/player/{targetPlayerMajorVersion}</path-element>
>            <path-element>locale/{locale}</path-element>
82c82
<             <manifest>/opt/flex_sdk_3/frameworks/mxml-manifest.xml</manifest>
---
>             <manifest>mxml-manifest.xml</manifest>