dynamic_cast – cpp

February 8th, 2010

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 <iostream>
 
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 ‘baseNot’ (of type ‘class baseClassNotWork*’) to type ‘class subBaseClassNotWork*’ (source type is not polymorphic)
     subBaseClassNotWork *subBaseNot = dynamic_cast<subBaseClassNotWork*>(baseNot);
    return 0;
}

Static_cast – cpp

February 8th, 2010

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

February 7th, 2010

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

February 3rd, 2010

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 !!.

Reinterpret_cast – cpp

February 3rd, 2010

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

February 2nd, 2010

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

February 2nd, 2010

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 ‘Circle’
poly.cpp:21: note:   because the following virtual functions are pure within ‘Circle’:
poly.cpp:11: note:      virtual void Shape::printName()

Because the Circle was not implementing what the parent class has defined as a pure virtual function.

In the code below I have placed some error values if you do not put “public” in the same places. These are typical errors that come from access to the objects internals that you are trying to access.

#include <iostream>
#include <string>
 
using namespace std;
 
class Shape 
{
  public:
      Shape(const string& conName) : name(conName) {}; 
      // create a virtual function so that it is implemented in the subclass
      virtual void printName() = 0;
 
  // protected, so it does not allow direct access, but subclasses can access it.
  protected:
      const string name;
};
 
// need to be "public Shape" otherwise
// error: ‘Shape’ is an inaccessible base of ‘Circle’
// it will not allow access to the Shape class.
class Circle : public Shape
{
  // you need to specify public for Cat to access Animal string name because that is protected
  public :
      Circle (const string& conName) : Shape(conName) {};
      void printName()
      {
	  cout << name << " class" << endl;
      }
};
 
class Rectangle: public Shape
{
  // you need to specify public for Dog to access Animal string name because that is protected
  // error: ‘Rectangle::Rectangle(const std::string&)’ is private
  public: 
      Rectangle(const string& conName) : Shape(conName) {};
      void printName()
      {
	  cout << name << " class" << endl;
      }
};
 
int main()
{
    Shape* shapes[2];
    shapes[0] = new Circle("Cirlce");
    shapes[1] = new Rectangle("Rectangle");
 
    for (int i =0; i < 2 ; i++)
    {
      shapes[i]->printName();
      // clean up the memory space.
      delete(shapes[i]);
    }
    return 0;
}

and here is the output

Cirlce class
Rectangle class

So in the example code above, the polymorphism is when for example the Rectangle class is defining the “interface” code for printName method.

Hello World

February 1st, 2010

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

When you want to compile up the source code, you will need to add the /opt/flex_sdk_3/bin (which is where the mxmlc command line compiler for creating the swf file) to the console

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>

Java applet – hello world

January 30th, 2010

A java applet is a web object that allows you to do some funky things within a web page, you could even have a game on the screen with a java applet. But as normal you have to start from the start as such, the most used starts are the classic “hello world” example.

In a java applet, it is basically a class called Applet that you extend from and this has all of base code inside it so you only need to implement the virtual functions

  1. init
  2. start
  3. paint
  4. destory
  5. stop

And these are the basic functions that allow you to call other classes of your choice. The init – (initialize), setups up the environment of your choice, start is where the application (GUI interface) will run within, paint is what is painted to the applet screen, destory is when you destory the applet you may need to clean up some code, stop is when the application/applet is stopped.

The main basic class will extend from a applet (java.applet.Applet) so you will need to import that class library

import java.applet.Applet;
 
// basic class extends the applet
public class HelloWorld extends java.applet.Applet {

and then implement the functions start,init,stop,destory and paint if required. Below is more code that will resize the basic applet object and display (paint) the words Hello World using the Graphics class object drawString method.

import java.awt.Graphics;		// need this for the Graphics part of the paint function
import java.applet.Applet;		// to extend from.
 
public class HelloWorld extends java.applet.Applet {
 
    // resize the screen 
    public void init()
    {
	resize(150,25);
    }
 
    public void start()
    {
    }
 
    // draw with the Graphics class object a string on the canvas, point 50, 25
    public void paint(Graphics graphicsObj)
    {
	graphicsObj.drawString("Hello World!", 50,25);
    }
 
    public void stop()
    {
    }
 
    public void destroy()
    {
    }
}

Is you save that as “HelloWorld.java” and then you need to compile it into a class file (which is a common object file that java can read to run within the virtual machine).

javac HelloWord.java

which will output the HelloWorld.class file, which you will need to include into the html code applet tag, below is the HTML code

<HTML>
<head>
<title>A hello world</title>
</head>
<body>
Test output of the program
<applet code="HelloWorld.class" width=150 height=25>
</applet>
</body>
</HTML>

The output would be

Test output of the program

Note: If you look at the source code of this page, it will say

<applet code="HelloWorld.class" codebase="/Appletsexamples/"  archive="HelloWorld.jar" width="150" height="25"></applet>

I had to add in the codebase and archive because of the hosting, to create a jar file you just need to do

jar cf <tarname> <file(s) name>
 
jar cf HelloWorld.jar HelloWorld.class

The jar file is basically a zipped archive.

const – constants in functions

January 29th, 2010

Const is a constant type, it makes what is talking to a constant value. The value cannot be altered in anyway, a good reason for this could be for a constant string for error codes or if the value of a variable needs to be checked but not altered in anyway.

Pointers can be constants too and also there are many places that you can put the const type. Here are some examples

// constant integer value
const int constValue = 3;
// normal value.
int Value = 10;
 
//pointers can be constants too
const int * pConst = &constValue;
//the pConst is a pointer to a const int value, the value pointed to cannot be altered, but the pConst memory location can to where it is pointing to.
int * const pConst = &Value;
// here the pConst value pointed to can be altered, but the memory location for the pConst for where it is pointing to cannot be altered (always pointing to the same place).
// of course you can have both.
const int * const pConstConst = &constValue;
// here it is a const int value that has a const pointer that is not allow to change.

You can also place const around the function definition as well, there are three places where you can place the const type.

const int returnValue(const int value1) const;

In the order of the const on the function definition list

  1. constant return type, cannot alter the returned value (unless you place it in a another variable)
  2. constant parameter passed, you cannot alter the value1 in this case
  3. constant “this”, this is the class that it is placed in and you cannot alter any values within that class

I have placed below some code that will hopefully explain more for the different types and also the error codes that come if you try and compile up if you are not obeying const rules and I placed the code below for what caused the error.

#include <iostream>
 
using namespace std;
 
// there are 3 different places you can put a const (constant)
// restriction on a function definition line.
// const int returnConstInt(const int value1) const
// {
// }
// in order of placement in the function definition line
// 1: cannot alter the returning value
// 2: cannot alter the passing value
// 3: cannot alter the values of "this" as being the class this
 
class constTest {
  private : 
    int value;
  public:
    constTest() { value = 0;};
 
    int returnIntConst(int passingValue) const;
};
 
// cannot alter any value for the class variables e.g. value in this case.
// of course you could do a const_cast.. which takes off the constant (const) type
int constTest::returnIntConst(int passingValue) const
{
    // cannot alter any value inside the function
    // assignment of data-member ‘constTest::value’ in read-only structure
    // value = 3;
    const_cast<int&> (value) = passingValue;	// take off the const type restriction
    return value;
}
 
int returnInt(const int value1)
{
  // cannot alter the parameter value1
  //error: assignment of read-only parameter ‘value1’
  // value1 = value1+ 2;
  return (value1 + 2);
}
 
// returning a constant value, which means that you cannot do anything to the 
// returning value, but if you assign that value to another variable you can
const int returnConstInt(int value1)
{
    value1 = value1 + 2;
    return value1;
}
 
int main()
{
    // cannot alter the return value of the returnConstInt 
    //  increment of read-only location ‘returnConstInt(3)’
    // int constValue = returnConstInt(3)++;
    int constValue = returnConstInt(3);
    // but you can alter the value of returning int from returnConstInt if passed to a variable
    constValue++;
    cout << constValue << endl;
 
    constTest cTest;
    cout << cTest.returnIntConst(10) << endl;
    return 0;
}

and the output would be

6
10