Archive

Archive for the ‘C/C++’ Category

Overloading Classes

May 29th, 2010 admin No comments

In OOP, it is a good practice to sometimes “overload” classes if you need to bring in information from the outside. For instance, if you want to include configuration variables in another class, you can “overload” that class with those variables. In this tutorial, I will explain how to do that in both PHP and C++.

Please note, before continuing, that I assume you are an intermediate to advanced C++/PHP programmer. Therefore, I will not go into great detail about how variables are set, etc. because you should already know how that works. We will jump right into the code now for an example as it’s usually the best way to explain these tasks.

PHP

<?php
/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Create our simple class
class OverloadMe
{
/**
* We would like a global var for the whole class
*/
var $var1;

/**
* Constructor
*/
function __construct($name){
$this->var1 = $name;
}

/**
* Name function
*/
function name(){
return $this->var1;
}
}

// Define the name variable
$yourname = "Dennis";

// We overload the function when we initialize it
$overload = new OverloadMe($yourname);

// Now let's get the output
print "Your name is ".$overload->name();
?>

Now, the procedure is very similar in C++, just classes work differently as you already know. I’ll give the C++ code now and explain it all at the end!

C++
src/main.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#include <string>
#include "overload.h"

int main(int argc,char* argv[])
{
std::string name = "Dennis";
OverloadMe overload(name.c_str());
overload.name();
return 0; // exit
}

src/overload.h

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#ifndef Overload_H
#define Overload_H

// Class definition

class OverloadMe
{
public:
// Constructor
OverloadMe(const char* namevar);

// Name function
void name();
private:
// A global var for the class
const char* var1;
};
#endif

src/overload.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Make the class work
#include <iostream>
#include <stdio.h>
#include "overload.h"

using namespace std;

OverloadMe::OverloadMe(const char* namevar)
: var1(namevar)
{
}

void OverloadMe::name()
{
cout<< "Your name is " << var1 << endl << endl << "Please hit enter to exit" << endl;
getchar();
return;
}

Now, for Windows users using MSVC++, this code will compile with a simple copy/paste. For *nix and BSD users, I’ve included a Makefile within the ZIP package for you to use when compiling. Basically, the compiler must compile each item as an object first, then it must compile the objects into the program file rather than compiling the .exe’s directly.

Well, I hope this is of some use to someone. The examples are fairly simple, but should explain the concept easily. As we can see in the C++ example, we initialize the class to a variable, and simply overload that variable at the time of initialization.

Regards,
Dennis M.

Overload_Tutorial

Categories: C/C++, PHP Tags: , , , , ,

Using Reference Operators in Functions

April 4th, 2010 admin No comments

Happy Easter everyone!

I felt today, being a day off, would be a good day to write something up. I’ve had a lot of inquiries lately about the use and functionality of reference operators (&) in variables. Well, basically, in common word, they replace the original variable. Of course, as usual, I have written up a sample code for you all to use, but first I’d like to explain a little bit more about these operators.

When defining a function, you always specify the format of function arguments. Take void test(int arg1,char* arg2); for instance. You have defined your function type “void,” the name “test,” and the arguments “int arg1″ and “char* arg2.” Now, the way these functions are defined, the function will proceed with the values inserted into the function and the function will only apply end values of these variables specifically to this function (unless type other than “void” is defined and you return an output; however, this output would still need to be defined in another function to transfer).

However, if you define a function such as: void test(int& arg1,char& arg2); it actually will append the variables that were used to make the input (thus the “reference”). So let’s take a look at some code, shall we?

/**
* Reference Operator Tutorial
*
* Author: Dennis J. McWherter, Jr.
* (C) 2010 DENNIS J. MCWHERTER, JR.
*
*/

#include <iostream>
#include <cstdlib>

using namespace std;

void deconstruct(float& x,float& y)
{
x/=y;
y*=x;
return;
}

void reconstruct(float& x,float& y)
{
const float z=x;
x*=y/x;
y/=z;
return;
}

int main(int argc,char* argv[])
{
// Define our main variables we'll be using
// Allow users to input!
float a,b;

cout<< "Enter your first number: ";
scanf("%f",&a);
cout<< "Enter your second number: ";
scanf("%f",&b);
cout<< endl << "Output:" << endl << endl;

const float a1=a,b1=b; // Define what our originals were! Please note that this is very recursive
// and can be done much easier with a function returning a value
// But that would ruin the entire point of this demonstration! :P

// Now we will do our actual functioning
deconstruct(a,b);
printf("%f / %f = %f\n",a1,b1,a);
printf("%f x %f = %f\n\n",b1,a,b);

// Define our "z" variable for here as well
const float z=a,w=b;

// Alright, take everything back to original form
reconstruct(a,b);
printf("%f / %f = %f\n",w,z,b);
printf("%f x %f = %f\n\n",(a1/a1),w,a);
return 0;
}

Now, as you can see, the variables are originally defined by user input. However, when taken to each function their values are changed (as can be seen by the printf values). That is what the purpose of a reference operator is. Now to reconstruct, we can use the same variables with opposite operations. The “const” defined in front of some variables protect them from being “referenced” (precursed with &) so their values will not change after they are defined. And as you can see in the final printf statement, (a1/a1) = 1 which is essentially what happens in the final steps of reconstruct().

As I mentioned, it is very recursive to do it this way (it would be best to simply print an output), but then that would defeat the purpose of this post. Also, for those of you wondering why I used printf(); instead of cout: there is no particular reason. Printf(); in this case (and honestly in most) is simply cleaner and quicker. The thing to remember, however, about printf(); is each function type (in this case %f) has a specific variable type that it can output. %f allows us to print float variables. For a more detailed list, visit http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

Below, you can download the script and a compiled *nix version.

Regards,
Dennis M.

Reference Operators Script

Categories: C/C++ Tags:

Multi-Argument Parsing

March 15th, 2010 admin No comments

Well, it has been some time since my last post since I have been (and still am) very busy, but I felt I needed to update! I wrote a quick script for you guys to help in any programming endeavors you may be having parsing your command line arguments in any command line program. This example merely shows how to simply print all the arguments given to a specified program, however, you can use this type of loop to do whatever you wish!

/**
* Process Command Line Args
* Level: Easy
* Author: Dennis J. McWherter, Jr.
*
*/

#include <iostream>

using namespace std; // I'll save myself some std::<> pain this time XD

void echo(char* str,int no)
{
int x = strlen(str);
cout<< "Argument Number "<< no << ": ";
for(int i=0;i<x;i++){
cout<< str[i];
}
cout<< endl;
}

int main(int argc,char* argv[])
{
for(int i=1;i<argc;i++){
echo(argv[i],i);
}
cout<< endl<< "Command line: "<< argv[0] << endl;
return 0;
}

As you can see, the first function is a loop which is given a char* array (it loops through each array value to print out the full string) and an integer position. The int allows the script to know which argument number it is processing (not that it is imperative in this case). In the int main(); function, this void echo(); function is called in another for(); loop. This loop begins at array position 1 (the array starts at position 0, however, arguments begin at 1; 0 is the program/command line name). Therefore, for each argument listed the program loops until it reaches it has no further arguments to parse.

There is your quick lesson today in processing multiple arguments in the command line! This should help many of you looking for a quick and easy solution to do this! The example code is provided below for download.

Regards,
Dennis M.

Parse Multiple Arguments

Windows Programming: Creating/Using DLL’s

September 8th, 2009 admin 2 comments

In the world of programming, there are MANY different types. Unfortunately, programming for some systems is different than others, but it’s things like that which keep the world turning. Today, we will discuss what exactly is a Dynamic Link Library (DLL) and how to use them to keep our programming easier and more organized. I will also include an Italian translation of this tutorial in the download source below! (Un traduzione del questo tutorial è in il download link per richiesta)

We’ll begin with what a DLL is and what it’s purpose is. A DLL is a wonderful tool to keep your programs organized by creating a DLL per set of functions. Also, it helps developers keep their closed source functions closed source, but also allows (with proper documentation/instructions on doing so) other users to use their work. Below we will give a few simple examples on how it all works!

To create the DLL we will be using Microsoft’s Visual C++. This is a free IDE compiler. I use it for any sort of Windows programming that I may do and will include the solution file in the download. Of course, I prefer GNU’s GCC which is also free, but the Windows ports of the compiler are not as good as the standard linux version.

The first note that I want to make is that if you’re making this project on your own (and not using my solution file), be sure to go to Project->Your Project’s Properties->Configuration Properties->General->Configuration Type and change it to “Dynamic Library (.dll)” otherwise it will not compile correctly.

Now in this tutorial, I am assuming you already know how to write programs, so this first file is test_dll.cpp. It contains the actual definitions, etc. of our functions:

/**
* Test Dynamic Library File
*
* (C) 2009 Dennis J. McWherter, Jr. All Rights Reserved.
*
*/

#define WIN32_LEAN_AND_MEAN // No need for the extra stuff.
// Non includere i file cui non hanno un scopo
#include <windows.h>
#include <iostream>
#include "test_dll.h" // Our header file
// Il nostro header file

using namespace std;

// Initiate the DLL (For programs)
// Iniziare il DLL (per i programmi)
BOOL APIENTRY DllMain(HINSTANCE dllHinst, DWORD reason, LPVOID lpvReserved){
// Use a switch to tell the program how to cycle the processes
// Usare un switch per fare il programma funziona
switch(reason){
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return true;
}

// The functions of our class. These are defined in "test_dll.h"
// Le funzioni del nostro class. Gli questi sono definire in "test_dll.h"

// Constructor
test_dll::test_dll(){}

// Basically a pointless function just to see how we can make them work together XD
// Una funziona senza la usa. è più di un demonstrazione.
char test_dll::func1(char lang){
return lang;
}

int test_dll::func2(float x,float y,char op){
// Simple math function!
// Semplice funziona della matematica
switch(op){
case 'a':
cout<< x << "+" << y << "=" << x+y;
return 0;
break;
case 's':
cout<< x << "-" << y << "=" << x-y;
return 0;
break;
case 'd':
cout<< x << "/" << y << "=" << x/y;
return 0;
break;
default:
cout<< x << "*" << y << "=" << x*y;
return 0;
break;
}
return 0;
}

Again, a fairly straightforward example. What you do have to notice in this that is different from most programs is that fact that we’re not really calling a “Main” function to be run. We call BOOL WINAPI DllMain instead. This next file is the header file. A rather important file overall as it let’s us know what to export.


/**
* Test Dynamic Library File
*
* (C) 2009 Dennis J. McWherter, Jr. All Rights Reserved.
*
*/

#ifndef HEADER
#define HEADER
// To keep the code clean we'll define this with a macro but this tells the processor
// to export whichever function/class it preceeds.
// Ci definiamo il questo con un macro ma ci vedremmo come lo funziona in più ritardo
#define EXPORT_DLL __declspec(dllexport)

// Now our class - If you export a class, all its functions come with! :) else do each function
// Adesso il nostro class! Se exporti un class poi i tutti funzione di lo sono exportare.
// se individuale ti exporti poi si deve __declspec(dllexport) per ogni
class EXPORT_DLL test_dll{ // = class __declspec(dllexport) test_dll{
public:
test_dll(); // Constructor/Costruttore
char func1(char lang); // First function definition/La definizione della prima funziona
int func2(float x,float y,char op);
};

#endif

The comments explain it, but it’s really worth going over again. EXPORT_DLL is defined just for the purpose that we could potentially have more than a single class to export. This goes both ways for the dllexport and dllimport options, so really, EXPORT_DLL just translates to __declspec(dllexport) which would also work if you replaced EXPORT_DLL. Now, compile that code and VC++ should provide you with a .dll file and a .lib file with whatever name you gave the project (in our case: “DLL_Tutorial.lib/.dll”).

Now, you cannot run DLL files by themselves; you need a client program (.exe) which is what we’re getting to now. For the sake of brevity, we will just make this a simple console program which runs the proper functions. Now, create a new project and make sure you copy the “DLL_Tutorial.lib” file into the source directory. You need the .lib file to compile the client program, but you only need the .dll to run the program.

So here is the client main file. A console program of course to keep things simple :) We’ll call this test_client.cpp

/**
* Test Dynamic Library File
*
* (C) 2009 Dennis J. McWherter, Jr. All Rights Reserved.
*
*/

#include <iostream>
#include <string>
#include "test_client.h"

using namespace std;

int main(){
// Create object to class
// Creare l'oggetto a class
test_dll test;

// Init var
string num1,num2,addition,subtraction,division,multiplication,ans,operation;
float x,y;
char choice[5], op[5]; // Allow more chars just in case - otherwise we'll break the script :(
// Permettere dei più caratteri così non ci romperiamo il script! :(
cout<< "Please select a language\r\n\r\nEnglish - en\r\nItaliano - it\r\n \r\nSelect: ";
cin>>choice;
switch(test.func1(choice[0])){
case 'i':
num1 = "Numero 1: ";
num2 = "Numero 2: ";
addition = "Per piacere selezi i tuoi numeri per aggiungiere";
subtraction = "Per piacere selezi i tuoi numeri per sottrarre";
division = "Per piacere selezi i tuoi numeri per dividere";
multiplication = "Per piacere selezi i tuoi numeri per moltiplicare";
ans = "La tua risposta: ";
operation = "\r\nPer piacere selezi il tuo operazione:\r\na - Aggiungiere\r\ns - Sottrarre\r\nd - Divisione\r\nm - Moltiplicazione\r\n\r\nSelection: ";
break;
default:
num1 = "Number 1: ";
num2 = "Number 2: ";
addition = "Please select your numbers to add";
subtraction = "Please select your numbers to subtract";
division = "Please select your numbers to divide";
multiplication = "Please select your numbers to multiply";
ans = "Your answer: ";
operation = "\r\nPlease select your option:\r\na - Addition\r\ns - subtraction\r\nd - Division\r\nm - Multiplication\r\n\r\nSelection: ";
break;
}

cout<< operation;
cin>>op;
cout<< endl << endl << num1;
cin>>x;
cout<< endl << num2;
cin>>y;

test.func2(x,y,op[0]);

cout<< endl << endl << "Type in anything to exit...";
cin>>op;

return 0;
}

Naturally, the header file that follows is test_client.h

/**
* Test Dynamic Library File
*
* (C) 2009 Dennis J. McWherter, Jr. All Rights Reserved.
*
*/

#ifndef TEST_HEADER
#define TEST_HEADER
#define DLL_IMPORT __declspec(dllimport) // Same concept as export
// Il stesso concepto come export

// Define the class

// What is the purpose of redefining? That's all you need to do is redefine structure ;)
// and not function :)
// Perchè ti deve ridefinire la class? Perché solo lo struttura si deve essere definire!
// e no funziona :)
class DLL_IMPORT test_dll{
public:
test_dll(); // Constructor/Costruttore
char func1(char lang); // First function definition/La definizione della prima funziona
int func2(float x,float y,char op);
};

#endif

Within these two files, they are essentially creating a calculator. Since I wrote this program in dual languages, I added SIMPLE (meaning hard-coded) dual language support into the program. Also, this gives a reason for the first function, just to see how one can use multiple functions from a DLL just as if they were in the source.

If anyone has further questions or is receiving errors, feel free to let me know and I will be glad to help! Now make sure, however, that everything is set right as well. I ran into an error compiling the client the first time because my project subsystem (found in project properties->linker->System) was set to WINDOWS rather than CONSOLE so it was looking for the WINMAIN where there was none. So just a word of caution to anyone trying this without my source and you are receiving a WINMAIN compilation error.

So the land of DLL’s really aren’t as complex as it seems. It’s simply a closed source utility which helps other developers in WINDOWS programs.

Regards,
Dennis M.

DLL Tutorial Source Code and Binaries

Converting a String to a Vector

August 24th, 2009 admin 1 comment

It has been a long while since I’ve posted a C or C++ tutorial, but here comes another one! I try to help with programming tips on various forums across the internet. I am a fluent English and Italian speaker, so naturally I work on forums of both languages. While browsing an Italian forum, I came across an interesting question. How does one convert a C++ string to a vector. I decided I would lend a hand, and it bears repeating on here.

Vectors can be used for various things in C++, but they are for the more advanced programmer really. They are not really necessary if it is not a complex program, but this tutorial could serve useful for many I’m sure.

I myself was at first puzzled by the question. I had never thought of a reason to do this and so, frankly, I never have. After some thought, it wasn’t too bad, but still an interesting concept. I’ll post the code below and then explain further below that. Comments are in both English and Italian. The reason being is what I previously mentioned about the original reason I wrote this code.

/**
* String to Vector Tutorial by Dennis M.
*
* un tutorial di microsonic.org
*
*/

// Include files ~ Includere i file
#include <string>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
// Declare Variables ~ Definire i varibili
string data = "one - uno";
vector<string> vect;

// Insert data into vector ~ Inserire l'informazione in il vector
vect.push_back(data);
data = "two - due";
vect.push_back(data);
data = "three - tre";
vect.push_back(data);

// Loop to view the contents of the vector ~ Loop per vedere i contenti di il vector
for(unsigned int i=0;i<vect.size();i++){
cout<< i << ": " << vect.at(i) << endl;
}

// Memory Management ~ Ci sicuriamo la memoria!
vect.clear();

return 0;
}

Now the code is pretty self-explanatory and the comments I think do a pretty good job. The only thing one may be perplexed about is where the functions and pointers come from. If you examine the documentation (header file?) for a vector, all is clearly defined. This example will also print the vector and clear it before it exits.

So I hope this post is of some service to someone and as usual, I have included the source and binaries in the post!

String to Vector Tutorial

Regards,
Dennis M.

Categories: C/C++, Italiano, Other Tags: