C++ Index

Delphi Index



Classes and inheritance in C++

Translating C++ Code into Delphi Pascal


A class is similar to a structure, with the difference that a class includes both private and protected data and functions which manipulate the data to perform a specific function.  It is typical for these classes, like structures, to be defined in a header file, with the sources for the functions included in a file with the same name with the difference the extension would be 'cpp' for the source and 'h' for the header file.  

Normally the function of a class allows access to the results of manipulation of the data while keeping the implementation private.  For example a class might manipulate a set of temperature variables and return energy as measurement of calories.  The implementation of the conversion and any variables these functions use would be private, and the result would be public.  In this way the actual source code which is also encapsulated in the class can be changed while the public interface remains the same, and a caller need not be concerned with the implementation of the embedded functions (only that the results returned are correct).  A large number of programmers could then contribute classes to a project and as long as the calling routines understand the input variables and the public output variables of the class the actual implementation does not need to concern any other programmer in the project (a similar principle applies to DLLs which have a public interface, but, because they consist of machine code, have a private implementation.)

The public section of a class consists of the interface, the part of the class that will be visible to other programmers who actually use the class.  This is kept separate from the private section of the class, which is invisible to the user and the sole responsibility of the programmer who designed the class.  The protected section consists of that part of the class that can be 'inherited' by a descendant class.

In C++ classes are declared with the class keyword...The following is an attempt at a very simple example.  (In this example I have decided to make the BIOS on the motherboard 'protected' rather than private....)

class AComputer {
   public :
     AComputer();
     bool OnSwitch;
     bool ResetButton;
     char Keyboard;
     bool Bootup(int partition);
   protected
     void BIOS();
   private
     char Keypressed;
     int ScreenPos;
     char GetKey();
     void WriteToScreen;
  }

Etc., etc...  The user here, like most computer users, only need to understand how to turn the computer on, and type on a keyboard, and doesn't need to be concerned about the 'private' implementation of the inner workings of the machine (only that the machine does in fact work, and that when a key is pressed on the keyboard it does in fact show up on the screen.)  

C++ classes, like Delphi classes, have a constructor, which is called when an actual instance of the class is created.  A default constructor will be called if none is specified, but if you want to initalize the class a custom constructor is required.  In the example above the constructor is 'AComputer()' and has the same name as the class (there is no 'constructor' keyword).  The constructor can use function overloading.  Functions are overloaded when more than one function exists with exactly the same name, but the variable declarations are different.  The compiler keeps track of which version of the overloaded function is being called by comparing the variables being passed in the code. If you take a look inside a DLL - or a C++ DLL interface, you will see 'mangled names', since no two functions can have the same name in C++.  For example a function might look like the following in code...

int Add(int x, int y);

float Add(float x, float y);

The compiler will mangle the names (usually a random looking mixture of garbage characters).  You will see the mangled name in the interface section of the DLL code.  Calling Add with two integers calls the first function and calling with floats will result in a call to the second function.  Constructors can be overloaded in the same way.  A default constructor need take no parameters and overloaded versions of the constructor are distinguished by the parameters they accept, as illustrated above.

Actual instances of a class are created in the same way that variables are created.

int x;

X is declared to be of integer type (notice that the syntax is backwards compared to Delphi).

AComputer ThisComputer;

The members of the class can be accessed using the dot operator.  Let's assume that  the class AComputer includes a public integer variable declared as 'y'.  (If 'y' is not public then the following code would generate a compiler error.)

int x = ThisComputer.y;

ThisComputer is an instance of the class AComputer.  In this the default constructor is used (either a default constructor, taking no parameters, supplied by the programmer, or the default constructor provided by the compiler).  If parameters are supplied then one of the overloaded constructors will be called.  

AComputer ThisComputer(16, 2, 9);

Here we assume that a constructor exists which accepts these parameters.  Constructors are never called directly, but rather are called automatically when an instance of a class is actually created in code.

The destructor is called just before an instance of a class is destroyed (goes out of scope, if the class was declared like a varable and is thus on the program stack, or is destroyed using delete, if the class was created dynamically and thus is on the heap).  Once again there is no keyword 'destructor' but rather the class name is used, preceded by tilde  ( ~AComputer()  ).  Destructors cannot be overloaded.  If a destructor is not provided the compiler will provide a default destructor.  One common use for a destructor is to prevent memory leaks by releasing any memory that was used by the instance of the class, but depending on the class implementation, a destructor may be called on to do any other final operations (save data, etc.)

The functions encapsulated in a class can access all the data and functions  in a class whether it is public or private, so long as an instance of the class exists.  Each instance of a class, however, exists seperately in memory (so the data values would be separate for each instance, unless declared using the 'static' keyword, which is a way of declaring global variables for the class - in this case all instances would share the static variables.  However, because an instance of the class could be expected to exist within the high speed cache, and the global variables could be anywhere in memory, the possibility exists that using static global variables in multiple instances of a class could cause cache misses.  I just mention this, since I have heard talk of how modern computers with a CPU memory cache choke a lot on global variables due to the high penalties caused by cache misses.  There is also something to be concerned about when one instance of a class changes a global variable which then is accessed by another instance of the same class - this problem is similar to that faced by multi-threaded programs which need to co-operate when sharing common data...)

Typically the 'public' functions of a class are the outside user interface, and the actual implementation of the task performed by the class is hidden.  These public functions could accept parameters and return results, either as the result of the function or as results included in the public variables declared for the class.  It should be noted here, that these public results stored in variables are only 'in scope' and thus usable, so long as the class is in scope and actually exists.  If the class is destroyed or goes out of scope, so do these public variables.  

A class is typically used in a program in three parts.  There is the header file, the source file for the functions of the class, and then there is the program code which actually uses the class.

For example you might see the following for the AComputer class)...

(acomputer.h  - the header file)

#ifndef acomputerH

#define acomputerH

constant strings  may be defined in the header file for the class (whever the compiler encounters the string SIZE it will substitute '22' in the source code ... it is typical for constants to be in uppercase but this is not a strict requirement (just remember that, unlike Delphi, C++ is case sensitive...)

#define SIZE 22
#define LENGTH 13

The class definition would then follow in the header...

class AComputer {
  public :
    ...public variables and access functions ...
  protected
   .....
  private
   .... the internal variables and workings of the class hidden from public access...
};
#endif;

In a seperate source file the actual definitions of the functions declared in the header file will be found with the same name as the header, but ending with 'cpp'...

acomputer.cpp ...

The include statements will be found at the head of the cpp file, and typically look something like this - note I am unclear as to why '<' is used for the standard include files and double quotes are used for the class header, but this is what I have noticed so I reproduce it here...

#include <stdio.h>
etc.
#include "acomputer.h"

next the code follows with the constructor having the same name as the class and the destructor preceded only by tilde as mention above.  Variables used by the class may also be set to certain values after the function header, seperated by a mandatory colon from the header and from each other by commas, except for the last, and then the function code itself follows...

AComputer::Acomputer(int x, int y) :
   q(16),
   w(12),
   cat(122)
 {
    ...the code ...
 }
void AComputer::Startme(int partition)
  {
     some code...
  }

We will assume then that all the functions declared in the header have been coded and the source file is complete.  Next a program will have to create an instance of this class in order for it to become useful...

In the calling program there will an 'include' section at the beginning of the code, and then the class is included using the following syntax that typically appears something like the following...

#include <something.h>
....etc
#pragma hdrstop
USEUNIT("acomputer.cpp");
#include "acomputer.h"

Note that there is no semicolon after the include statement for the acomputer.h header file..

Next there follows a list of the functions included in this particular source file (note that this is different from the source code for the class since the functions are declared in the header file which is then included in the source file..)  Let's assume that our program has the typical 'main' file (which is not declared in the list of functions at the top of the file) and also two functions called 'thisone' and 'thatone' ... The list of function declarations  is followed by the actual description of the code, starting below with the 'main' function...

int thisone(int x);
int thatone(int y);
void main(int whatever)
 {
   main code starts here...blah blah
 }
int thisone(int x)
 {
  code for this one..
 }
etc., etc. ...

In code we want to create an instance of the class. We could do this using pointers.

AComputer* ThisComputer = new AComputer(constructor variables here);

The members of the class can then be accessed using pointer coding...Let's suppose the class had a public function 'CPUTemp' which returned an integer...

int currenttemp = ThisComputer->CPUTemp();

Public variables can also be accessed using the same pointer syntax...

Because this instance of the class was created dynamically (on the heap) when we delete it we are also calling the destructor for the class...

delete ThisComputer;

You might see code that inherits from a class and so I include a brief discussion of inheritance from classes here as well...

Let's suppose that we want to 'inherit' code from the AComputer class to make a new class called 'MacComputer'.  The base class would be 'AComputer' and the derived class would be 'MacComputer'.  We would indicate that inheritance is at work in the following way...

class MacComputer : public AComputer {
  public
     MacComputer(maybe some variables here);  ...note that this is the constructor...
     virtual char GetKey(some vars);   ...note this is 'virtual' so we will 'override' the original Acomputer code by writing a new routine for MacComputer ...
   protected
      etc...
   private
     virtual int something(variables);  another routine is virtual and will be replaced for MacComputer

The descendant class would then call the constructor of the base class in its constructor code.

MacComputer::MacComputer(int x) :
   AComputer(int x)
 {
     constructor for MacComputer code is here
 }
   

If the default constructors provided  are used then this would not be neccesary.

If we wanted to literally inherit anything from AComputer then the virtual keyword is not used and the original code is simply inherited from the base class.  We can also add new routines not included in the orignal class by declaring them without using the virtual keyword (which is not needed since in the case of a new function or variable it is not necessary to indicate that we overriding the code in the base class).  Note that the virtual keyword must be included for those routines in the header file of the original base class 'AComputer' and the declaration and the variables must match in the base class and in the derived class (the header of the two functions must match) and then the function can be rewritten in the derived class.  Because the derived class provides its own version of this 'virtual' function this indicates to the compiler that the derived (virtual) version of this function is to be called in all derived classes, and not the original function by that same name in the base class.

The functionality of the original virtual can also be included in the new (virtual) function followed by and/or preceded by additional code in the source file in the following way.

char MacComputer::GetKey(some variables)
  {
    some extra mac code here...
     AComputer::GetKey(some variables);  ...include the base code here...
     now add some more mac code...
  }

Note that 'GetKey' must be in the protected section of the AComputer code and not the private section.  What is in the protected section can be accessed by descendants that have inherited from a class but what is in the private section even descendants cannot access, so this would not work, and indicates one of the key differences when designing a class between putting something into the private section or the protected section of the class.  The descendants of this class would then access the 'private code' in the same way as any other outsider (through the interface provided by the base class).  So 'private' functions and data  in a class are 'hidden' as are protected functions and data, but those that are protected are available for inheritance.

Note that it is not required to call elements in the base class using the 'scope operator' if the elements have not been over ridden.  For example we must call AComputer::GetKey(blah) because GetKey has been over ridden.  Let's suppose that we inherit (without overriding) something called GetMouse(blah).  We could simply use GetMouse (rather than AComputer::GetMouse(blah) ) because there is no need to indicate the scope in this case, since there is only one 'GetMouse' to consider.  If the scope operator is not used, and a function has been over ridden, then to avoid ambiguity the compiler uses the descendant function, since it is considered to be more 'in scope' than the 'further away' ancestor or base class.

If we wanted to use 'MacComputer' as the base class for, say, 'Mac64Computer' then it would turn out to be the case that Mac64Computer would ultimately be a descendant of AComputer as well.  Thus inheritance can be thought of as being like a tree, with a root base class, and many branches coming off of this root in a tree like structure.

It is also possible for descendant classes to use multiple inheritance.  For example let's suppose that a new computer was to be designed that was to inherit all the features of a Mac and an Apple.  Let's call this new computer the Macle.

class Macle : public MacComputer, public AppleComputer {
  public
    Macle(whatever vars);
   private
etc.etc.

By inheriting both the Mac and the Apple classes and overriding whatever virtual functions are required a new computer class is created (the Macle) which combines both the previous classes.


Previous Page - C++ header files

C++ to Delphi Index      Delphi Index



A Unified Field Theory

failed_gravity_theory.gif - 10361 Bytes



The Unified Field Theory
is also available as a zip file ->
unified.zip

Introduction :The Pioneer Effect and the New Physics. A brief description of the new physics required to explain the 'Pioneer Effect', which is the constant deceleration of space craft as they fly through space.






Principles of Evolution: A Study in the Evolution of Bedbugs



A couple of years ago my bedroom was invaded by bedbugs. There were two variant genetic lines. One type of bedbug was an enlongated, thin, tubular insect, and the second genetic line was a flat, perfectly circular insect. The result of the cross breeding of these two genetically distinct variants was the production of a bedbug with charcteristics of both, an enlongated, flat bedbug with a central bulge (such that the shape of the bedbug was somewhere between 'long' and 'circular'). The long skinny bedbugs were such strange and unfamiliar looking insects that at first I did not recognize them as being bedbugs, and considered them to be a seperate species of insect. However, as the photographs of bedbugs above indicate, enlongated and skinny bedbugs are not uncommon, and the photographs also show the variants that are produced by genetic combinations that result in an insect somewhere in between 'circular' and 'enlongated'.

Therefore it is my hypothesis that evolution occurs by means of the transfer of dominate genes, with the production of such dominant genes being the product of 'biological algorithms', a genetic software program that brings physical characteristics into harmony with behavior, such that when behavior changes, and a conflict then exists, this acts as a trigger and causes the release of dominant genes. The result is rapid evolution of species. The bedbug is a relatively new insect, not the product of millions of years of evolution but rather an insect that is evolving in real time. The newly emerging dominant form of the insect is the flat, round ciruclar insect, well adapted to living in human bedrooms (it is flat, rather than tubular, thus allowing it to hide in the smallest cracks, living a stealthy lifestyle, and it is round, which gives the insect a maximum storage capacity such that it must endanger itself only a few times a month by emerging to feed.

Other examples of rapid evolution include the development of long legs in an invasive species of toad in Australia. As the toads move into the mountainous regions of Australia, and their behvaior changes, making them 'climbing toads', over the course of just a couple of decades the toads in the highlands have grown long legs specially adapted to climbing. It is worth noting here that the toads are poisonous, and are a successful invasive species because they have no natural predators in Australia, and so it would not be the case that the toads with long legs were 'the fittest survivors', because all the toads are survivors, and therefore predation does not explain the rapid emergence and spread of such well adapted, long legged toads. Once again we see evidence for the existence of biological algorithms and the rapid spread of dominant genes through a population, which once introduced proceed to overwhelm the older genes which are being replaced (making toad long legged and a bed bug round and flat).


A Theological Experiment

My interest in pursuing the Unified Field Theory is spurred on by my need to discover the theoretical explanation of a new form of propulsion (as explained on this page: Why the Unified Field Theory?). The experiment involving the bedbugs came out of nowhere.

I also believe that it is possible to justify theological propositions using experimental methods. If a thing is an objective truth then it can be verified and proven true by means of experimentation. Such a theological proposition is of more value than a ‘divine revelation’, since such revelations depend upon nothing more than establishing authority figures which requires the creation of artificial hierarchies, for the only reason why I might be encouraged to believe an authority figure who orders me to believe unsubstantiated opinions is if I could somehow be convinced that this authority possessed a mind that was somehow superior to mine, and thus was fit to express opinions as though opinions were unquestionable facts and thus worthy of being elevated to the status of absolute dogma.

There is a self evident human inequality which is visibly apparent. Some people are ‘beautiful’ and thus are the true elite on this planet, and some people are not. It is this sexual inequality and the degeneration that follows upon beauty that is the true driving force behind all the evil that happens on earth. The need for ruthless oppression and the pursuit of wealth and the consequent creation of suffering and poverty which must follow upon this practice is for the purpose of creating an artificial alpha elite.

The true elites are the young and the beautiful. The artificial elite are the rich and the wealthy. The elite aging rich artificial alpha male has no good looks, for he is physically degenerate, but he will be found escorting beauty because he has a beautiful wallet. If he loses his wallet he will be found at home with all the other unattractive aged beta males sitting in a rocking chair watching reruns of Bonanza. No money, no sex. It is for this reason that the alpha males are found to be so ruthless and so violent in pursuit of their goal. The alpha male has fallen. The beta male has arisen and now the whole planet is full of ruinous destruction for it.

We see in religion a confused and contradictory reaction to this reality. On the one hand religion preaches a sexless heaven where castration and the clitorectomy create ‘pure spirits’. Muslims throw women under sacks. On the other hand religion supports hierarchy and is the prop of the elite alpha male. It is for this reason that religion is incoherent when it comes to speaking about sex.

Now we see this same principle at work in all of nature. Guppies dance and show off their colorful tails and the guppy who dances with the most colorful tail is the sexually successful guppy. Therefore it is the doctrine of the ruthless oppressor which teaches that the solution to human sexual violence is to be found in castration and the creation of pure ghosts. This would be equivalent to damning an aardvark for having the ‘sinful aardvark nature’ or prosecuting an anteater for the high crime of ‘ant genocide’.

Therefore it was my theological hypothesis that the correct solution to this problem is to give every guppy a beautiful colorful tail. I compare this solution to the classic religious solution which is to cut off every tail since having a tail is ‘sinful’. If having a tail is sinful then God must be sinful for no human being has any choice in deciding whether or not they would be born with a colorful tail, or whether they would not.

When I was young I was a beautiful guppy with a lovely tail. So everyone seemed to think. I am older now. My nose became very badly sunburned and destroyed. It seemed good to me to test my hypothesis by using these ‘biological algorithms’ to correct this problem. I healed half my nose as you can see by the line separating the still very dark patch on the side in the photograph below.





I documented my experiment on these pages. one two t hree four fi ve six


I have confirmed to my own satisfaction that my theological proposition is correct and that religious dogma is erroneous, being based as it was upon nothing more than ‘divine revelation’ which is just a form of opinionated speculation. For the time being I am not continuing this experiment, for I must wait until the weather on this planet improves, and the dark clouds of ruthless oppression break letting a little sun shine come through so that I can show the world the truth about God, by showing people how God goes about giving an old guppy back his beautiful colorful tail.


Until then I will have to sit on the sidelines, while all my scientific breakthroughs are deliberately ignored, while I wonder to myself what ever in the world could be wrong with the human race, because what this all will prove at the end of it all is that there definitely was something wrong with the people on this planet.