Monday, March 22, 2010

OOP344 - who needs default constructors anyway?

i always had a feeling that default constructors were pointless. I don't know, something about making a function that sets everything to null seems... meaningless? Fortunately, I've learned an alternative! Let's say we have a class called, for instance, Poop (lol). Inside Poop, we want to keep color (char*) and size (int). If we were to use a default constructor AND an argument constructor, our prototypes would look like this:

Poop();
Poop(char* color, int size);

This method would leave us having to write the same constructor twice, except the argument constructor would assign values other than 0.
In order to avoid the redundancy, we can write 1 arguement constructor with this little tweek:

Poop(char* color = 0, int size = 0);

If Poop() is called without arguments, the constructor will automatically use the default values provided in the declaration! Genius, I know!

Monday, February 8, 2010

OOP344 - fardad, i accept your putint() challenge!

this function was harder than i expected. In order to convert a number to a character, all you have to do is add 48 (this is because 0 on the ascii table is 48, 1 is 49, etc.). So as long as you are sending the putint function a 1 digit number, this will work. However, for the keys that are 4 digits long (i.e: RIGHT_KEY = 1077), it gets a little more complicated.

This took me a while to figure out and i must say, it's genius :). First what you have to do is: seperate the digits. This is where being good with numbers really helps.
(i'm not going to write code, instead I'll give you a mathematical view point)

if you divide a number by 10, the decimal moves one point to the left:
1077 / 10 = 107.7
In order to get the decimal point i used a float, however that caused problems because float are never exact. So, i made two temporary int variables and did this:

1. temp = 1077 <- this is the integer being sent to the function
temp / 10 = 107 <- integers truncate decimal points
temp * 10 = 1070
2. temp2 = 1077 - temp
= 7
Hooray, i got the first digit separated. Now, just do char = temp2 + 48; and your first digit is successfully converted. Repeat this process for x amount of times and your string contains a 4 digit number. BUT WAIT, how do i determine x? dividing by 10 again.
make a while loop where you divide temp by 10 while temp > 0 and do an i++ to get how many digits are in the number. you can now use i for a for loop.

There you have it, a putint function that converts an integer into a string without using extra libraries (there is no atoi() or sprintf()).

Monday, January 11, 2010

Welcome!

Welcome to Dan's Programming blog!