Archive

Posts Tagged ‘C++’

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: , , , , ,

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

Some Topic Ideas!

May 23rd, 2009 admin No comments

Hey guys, sorry for the long delay in updates, I’ve been taking topic ideas. None have quite struck my fancy (so to speak) where I feel they would make some great discussion topics. So please, send me some suggestions via email (dennis [at] microsonic [dot] org)! If I don’t get any great ones in the next day or so (well, either way really), I’ll be posting my “Deep Links Mod” for phpLD 2.x.x. Since there already is a great working one for phpLD 3.x.x, I will be releasing the one I wrote for a recent project I just finished up!

Regards,
Dennis M.

Categories: Other Tags: , , , , ,

The For(); Loop

May 13th, 2009 admin No comments

Many new programmers are perplexed by the “for” loop. However, it is one of the most essential and powerful tools in any developer’s arsenal. Without it, efficient and clean programming would not be as possible. Early on, most developers seem to stick to the while(); loop. I mean sure, while(); is great for some things, but may not exist in some programming languages and not to mention won’t work for everything you need.

Let’s begin by going into the basics about the for(); loop. Well really, a lot depends on the programming language (I will provide both PHP and C++ examples in the source file). But more or less, the for(); loop is simply iteration. It will run until its defined limit is hit providing whatever results you wish. We’re going to do this in more standard languages (e.g.: C/C++ and Java) instead of PHP for mass compatibility. Just note, if you’re looking to do this for php, you do not need to define the type of variable, and your variable will just start with the “$” symbol. So for example, PHP would be for($i=0;…;…){}.

Now we’re going to write a sample program and break it down:

for(int i=0;i<=5;i++){
std::cout<< "This is line number "<< i << std::endl;
}

Now as most of you may have noticed, this is a C++ example, but will effectively explain how the loop works for ALL programming languages!

int i=0; – This simply defines the variable and starting place (0 in this case). In PHP you would simply use $i=0; and so on for the rest of the statements.
i<=5 – This tells the loop when to stop (This <= symbol means less than or equal to). When i>5, the loop will stop and proceed on to the rest of the code.
i++ – This tells what the loop should do after every time it is run. In this case, we’re using i++ which means to add 1 each time around.

Now those are the basics to the loop. What lies within is just simply the code to be executed, which could of course have conditionals and such within it as well (e.g.: if(), etc.). So now we’ll move on to a more complex example.

unsigned int choices=5;
char* choice = new char[choices];
for(int i=0;i<=choices;i++){
std::cout<<"Please enter a value: ";
std::cin>>choice[i];

if(!choice[i]){
std::cout<<"No value for choice "<< i<< std::endl;
}
}
for(int i=0;i<=choices;i++){
std::cout<<"Choice "<< i<<" was "<< choice[i] << std::endl;
}

This will store an array of choices and then after entering them, they will be printed back!

In the source below, all working examples will be provided!
For(); Loop Tutorial

So, that basically wraps everything up! If you need anymore clarification, just let me know.

Regards,
Dennis M.

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