C++

C++ is an object-oriented language created at Bell Laboratories to add object-oriented programming to their C language. To properly add the object-oriented properties to the language, the design engineers modified the compiler to be much stricter in following the rules Than the C language, especially about the casting of variables. For this reasons, many engineers that were still using C would use the C++ compiler to find errors that might cause problems later. Examples of some of the problems that could occur are mixing up signed and unsigned integers. Computers smallest storage units are bits and bytes. One bit can be considered one gate or switch, which can be either on (1) or off (0). Now, a byte is 8 bits. A signed byte can range from -127 to +127, while an unsigned byte can vary from 0 to 255. C++ is much stricter on enforcing variable integrity, so it becomes more difficult to mistakenly use an unsigned integer as a signed integer.

The following sections include descriptions of some of the items I needed to learn to transitions from C to C++. The start of the sample code here is at Common Sample.

Virtual Function and Pure Virtual Function

Virtual Functions are procedures defined in a class that should be redefined by subclasses.  There are two ways of writing Virtual Functions, the first is with a defined body, or default implementation and the second with no body.  The pure virtual function is set equal to 0.  The Virtual Function allows the user to overwrite the class definition for this function. The Pure Virtual Function forces the designer to implement the function in the subclass.  Any Parent Class that includes any Pure Virtual Function cannot be instantiated on its own.  Neither can any subclass be instantiated if the Pure Virtual Function is not defined.

Example of code:

Class Header Example (example.h)

{
  Public:
    /* Standard (non-virtual) procedure that subclasses can use.*/
    Const char* NonVirtName() {return “Base Defined Function”’}
    /* Virtual function, can be overridden, but has default     */
    Virtual char* VirtClassNameReturn() {return “Example”;}
    /* Pure Virtual, subclass must define. defined here as =0   */
    Virtual char* PureVirtualReturn() = 0
}

Public and Private Functions and Encapsulation

Each class can have Public and Private Functions and Data.  The Public Functions and Data are designed to be used by and visible to the Public.  The Private Functions and Data have some more restrictions.  But definitions for both are visible in a standard  header.  That is why, when we designed libraries for SoftBench, we had two headers.  The first header, with both the Public and Private Functions and Data, was used for internal development.  The second header was what we included in the library package, so that the users could interface with the appropriate Public Functions.  If we had any virtual functions, we always defined a default action, so that each class can be instantiated. If the virtual function was set to “0” then the subclass must define the action that function will take before the subclass can be instantiated.

Encapsulation is the use of internal Functions and Data that are not visible to the outside user.  There was some information in the classes I developed that I did not want the user to be able to either see or modify.  Normally creating functions and data as Private will restrict their usage in Subclasses, but there are some ways around these restrictions in inherited classes.  I do not know the exact methods at this time, but I am sure that I could remember a few, if needed.

Singleton

A singleton class is where there is only one resource available and you do not want more than one function accessing the resource at a time.  The definition is through the Instance() function being defined as Static.  This allows for only one class to be instantiated at a time.  All communication to this item must go through this one class.  There are two ways of having this available, either having the instantiation done under the main() program or having an associated flag to determine if this class is being used by another process.  In either case, there needs to be an easy way for any function to determine if this resource is currently being used.  There could be a wrapper class that passes on this information and does not allow the Singleton class to be instantiated more than once.

Overload, Override, and Hide

Overloading is the term with which I am familiar.  Overriding and Hiding are newer (post 2005) concepts that are built on Overloading.  Overloading is what you do to Virtual Functions or Operators with a default implementation.  For example, the mathematical operators (+, – , *, /, <, >, =, ==, <=, etc.) and the function “print” are contextually overloaded, depending on the data types that are used with the operator or function.  For example, if you add two small integers, you want to get a small integer in return.  However, if you add two values that include Dollars and Cents, you want to get the proper monetary value in return.  Since then, the override and hide functions have been added.  In the example code I have seen, I have not see enough differences between overloading and overriding to describe the difference.  The functionality appears to be the same, but the main difference is that the override function has a reference back to the Base class virtual function definition.  If you could explain the difference, I would greatly appreciate it.  As for Hiding, this is defined by adding the keyword “new” at the end of the function definition.  In the examples I have seen, if the function is defined as “Virtual char*VirtClassNameReturn() new” the function will perform the default function of the Base class.  This again, is only what I have learned from my brief exploration today and I would love to hear a better definition.

Safely Passing a String Reference

The way I have safely passed strings is to pass the address,  &address, of the string to the function and label the address as a const.  If a variable is defined as a const, it can only be set once and cannot be changed afterwards.

Structs (Structures) vs Classes

Structures and Classes, according to the internet, are basically defined as being the same.  However, the way I have seen them used and the way I use them are slightly different.  I only use structs to be a place to store needed data.  I may include a struct in a class and I have a constructor and destructor in a struct to initialize the data and allocate (malloc) any needed space for items like strings, but I use a class for any manipulation of the items in the struct.  I never allow a user of my library to see my structs, but have a “wrapper” class to allow the interface to the public.  This probably gets back to the differences between what you consider public and what you consider private and why I thought I heard you refer to  structs as private classes.

Common Sample

There is one common application that I have written in Java and Python. Here is the C++ version. Please notice the two methods for printing information are in these files, one is <I>cout</I> and the other is <I>printf</I> (or some variation thereof). Look for them. Compare and contrast the implementation in different languages. One of the digest differences is the “header” files need to be included to tell the module with the call on what needs to be specified to complete the call. For a more complete tutorial, you might read the C++ Language Tutorial.

MyBasics.h

Notice the flag at the beginning to prevent the header file to be included more than once.

#pragma once
#include 
#include 
#include 
#include              // this is wehre cout is definded.
using namespace std;            // But this is needed to say in is part of the std definitions

class MyBasics
{
public:
	MyBasics();
	virtual ~MyBasics();
	static int countDigits(int n);
	static bool isInteger(string n);
	static bool isPerfect(int n, bool prFactors = false);
};

MyBasics.cpp

/***************
 * NyBasics.cpp - 15 ctober 2016
 * Author: Wayne Cook
 */
#include "MyBasics.h"


MyBasics::MyBasics()            // In C++, Constructor needs to be defined.
{
}


MyBasics::~MyBasics()           // In C++, Destructor also needs to be defined.
{
}

int MyBasics::countDigits(int n)
{
	//string buffer;
	//return(strlen(_itoa_s(n,buffer,20)));
	int checkNum = n, count = 0;
	while (checkNum > 0) {
		checkNum /= 10;
		count += 1;
	}
	return(count);
}

// Check if input is integer
bool  MyBasics::isInteger(string n) {
	bool returnVal = true;       // Set the answer is True, unless an exception occures
	try {
		int number = atoi(n.c_str());
		if (number <= 0) {
			returnVal = false;  // Sometimes atoi reurns 0 for a non-integer input.
		}
	}
	catch (invalid_argument) {
		returnVal = false;    // A non - integer input was found
	}
	return(returnVal);
}

bool MyBasics::isPerfect(int n, bool prFactors)
{
	int sum = 0;
	if (prFactors) {
		cout << "Factors for " << n << ": ";  // I could also use fprintf() instead of cout.
	}
	for (int factor = 1; factor <= (n / 2); factor++) {
		if (n%factor == 0) {
			if (prFactors) {
				cout << factor << " ";
			}
			sum += factor;
		}
	}
	if (prFactors) {
		cout <<"with sum " << sum << "\n";
	}
	if (sum == n) {
		return(true);
	}
	else {
		return(false);
	}
}

Febonacci.h

#pragma once
class Fibonacci
{
public:
	Fibonacci();
	virtual ~Fibonacci();
	int* fibonacci(int n);

};
#define MaxLength 512

Febonacci.cpp

#include "Fibonacci.h"



Fibonacci::Fibonacci()
{
}


Fibonacci::~Fibonacci()
{
}

int* Fibonacci::fibonacci(int n)
{
	int* list = new int[MaxLength];       /* Create storafe for array of 100 integers         */
	int index = 2;           /* Keep track of what member of the array to fill.   */
	if (n <= 0) {
		list[0] = 0;         /* I prefer to have only one return per function     */
	}
	else if (n < 2) {
		list[0] = 1;         /* You may prefer return's though, your choice       */
		list[1] = 0;
	}
	else {
		int current, next; /* Needed for calculating the sequence           */
		current = 1;
		next = 2;
		list[0] = current;
		list[1] = next;
		while (next < n) { list[index] = current + next; current = next; next = list[index]; index++; if (next > n) { /* There is a chance that next will be larger than n  */
				break;      /* Do not include it in the list.                     */
			}
		}
	}
	list[index] = 0;		/* Set endflag                                        */
	return(list);           /* This is my one return for this function            */
}

FebonacciSequence.cpp

This is the file that contains the main() definition. Notice that unlike Java, it does not need to be embedded in a class definition.

/**
* Fibonacci Sequence - 17 October 2016
* Author: Wayne Cook
* Main program that controls flow.
*/
#include "Fibonacci.h"
#include "MyBasics.h"
#include 
#include 
#include 
#include              // this is wehre cout is definded.
using namespace std;            // But this is needed to say in is part of the std definitions

int main(int argc, const char* argv[]) {
	Fibonacci* fibonacci = new Fibonacci();
	char buffer[MaxLength];
	int number;
	int* list;
	bool numCheck = false;
	char* enterSting;
	char* perfTest;
	// loop until a string that only has numbers is entered.
	enterSting = "Enter a number";
	while (numCheck == false) {
		printf("%s: ", enterSting);
		fgets(buffer, MaxLength, stdin);
		numCheck = MyBasics::isInteger(buffer);
		enterSting = "There is a problem with your input, please re-enter your number";
	}
	number = atoi(buffer);
	list = fibonacci->fibonacci(number);     //fibonacci is an instantiation of the Fibonacci class, must use -> to access method.
	// Print the sequence
	printf("The number %d has the febonacci sequence of:\n", number); // printf statements have one quoted string and references to types of variables.
	for (int i = 0;i<MaxLength;i++) { if (list[i] > 0) {
			printf("%d ",list[i]);
		} else {
			printf("End\n");
			break;
		}
	}
	// Determine the perfect numbers (sum of factors == number) in this range
	printf("The perfect numbers are:");
	for (int factor = 1; factor <= number; factor++) { if (MyBasics::isPerfect(factor)) { // MyBasic has not been instatiated, must use :: to access method. printf(" %d",factor); } } printf("\n"); // Use the optional parameter to print the factors of the number if (MyBasics::isPerfect(number, true)) { perfTest = "is"; } else { perfTest = "is not"; } printf("Number %d %s a perfect number\n", number, perfTest); printf("Press Enter to exit program: "); fgets(buffer, MaxLength, stdin); fibonacci->~Fibonacci();                     // Make sure class is freed up.
	return(0);                                  // Return an integer to exit.
}

Output Console Window

Microsoft Console windows do not allow copying of material. I hope you can read the window.
C++ Fibonacci Output