12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

86 Day 3<br />

HOUSE RULES: POINTERS AND DYNAMIC MEMORY ALLOCATION<br />

■ Be sure to <strong>in</strong>itialize po<strong>in</strong>ters to 0 if they are not used right away.<br />

■ Be sure not to delete a po<strong>in</strong>ter twice.<br />

■ It is OK to delete po<strong>in</strong>ters set to NULL or 0.<br />

■ Set po<strong>in</strong>ters to NULL or 0 after delet<strong>in</strong>g them.<br />

■ Dereference po<strong>in</strong>ters to obta<strong>in</strong> the object the po<strong>in</strong>ter po<strong>in</strong>ts to.<br />

Functions <strong>in</strong> <strong>C++</strong><br />

A function <strong>in</strong> <strong>C++</strong> can do everyth<strong>in</strong>g that a function can do <strong>in</strong> C. In addition, <strong>C++</strong> functions<br />

can do th<strong>in</strong>gs that functions <strong>in</strong> C cannot. Specifically, this section looks at the follow<strong>in</strong>g:<br />

■ Function overload<strong>in</strong>g<br />

■ Default parameters<br />

■ Class member functions<br />

■ Inl<strong>in</strong>e functions<br />

Function Overload<strong>in</strong>g<br />

<strong>C++</strong> allows you to have functions that have the same name but take different parameters.<br />

Function overload<strong>in</strong>g is when you have two or more functions with the same name<br />

but with different parameter lists.<br />

NEW TERM<br />

NEW TERM<br />

Functions that share a common name are called overloaded functions.<br />

On Day 1 I showed you an example program which conta<strong>in</strong>ed a function called multiply().<br />

Not surpris<strong>in</strong>gly, this function multiplied two values together. The function took two<br />

<strong>in</strong>tegers, multiplied them, and returned the result. But what if you wanted to have the<br />

function multiply two float<strong>in</strong>g-po<strong>in</strong>t numbers? In C you would have to have two functions:<br />

// declarations for a program written <strong>in</strong> c<br />

<strong>in</strong>t multiplyInt(<strong>in</strong>t num1, <strong>in</strong>t num2);<br />

float multiplyFloat(float num1, float num2);<br />

short multiplyShort(short num1, short num2);<br />

Wouldn’t it be a lot easier if you could just have a function called multiply() that would be<br />

smart enough to know whether you wanted to multiply shorts, <strong>in</strong>ts, or longs? In <strong>C++</strong> you

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!