Understanding Functions in C++ (UFC)

Substance:

  1. Definition of Function
  2. Purpose of creating a function
  3. Function Structure
  4. Functions with Parameters
  5. Function Declaration / Prototype
  6. Default value of parameter
  7. Passing parameters by value
  8. Passing parameters by reference
  9. Functions with Return Values
  10. Function without Return Value
  11. Variable Scope
  12. Function Overloading

1. Understanding Functions

  • Functions are blocks of programs designed to carry out specific tasks.
  • A function is a block of statements containing a number of statements packaged in a name that can be called multiple times in multiple places in a program.

2. Purpose of creating a function

  • To reduce repetition of the same program
  • So that the program becomes structured, neat and easier to develop.
  • To facilitate program development, because the program is broken down into several smaller programs.
  • To save program size, this will be felt if there are several sequences of the same instructions and are used in several places in the program.
  • Function declaration/prototype.

3. Function Structure

A simple function has the following writing form:

return_type nama_fungsi(parameter) {
pernyataan
}

Information:

  • return_type is the return value when the function is called
  • function_name, usually adjusted to the function's use, but may be written freely as long as no spaces are used and the function names have their own meaning. 
  • parameters/arguments, placed between brackets after the function name, arguments are used as input values ​​for the function and can be made more than one or none at all.

To call a function, use the function name and argument definitions if needed. Consider the following example:

#include <iostream.h>
#include <conio.h>

void hello() {
cout << "Hello Everyone\n";
}

void main() {
hello();
hello();
getch();
}

Output:

Hello Everyone
Hello Everyone

4. Functions with Parameters

Parameters are values ​​that we can input into a function. We can define any number of parameters as needed.

There are two types of parameters, namely: 

  • formal parameters, namely variables contained in the function definition.
  • actual parameters, namely variables or values ​​used when calling a function.

Consider the following example:

#include <iostream.h>
#include <conio.h>

void tambah(int a, int b) {
cout << a + b << endl;
}

void main() {
tambah(10, 12);
tambah(100, 200);
getch();
}

Output:

22
300

5. Function Declaration / Prototype

Function prototypes are used to declare to the compiler:

  • Function name
  • Return value of the function
  • Function return value data type
  • The number of parameters/arguments the function uses
  • The data type of each parameter/argument used by the function

Example:

#include <iostream.h>
#include <conio.h> //definisi prototipe

void tambah(int a, int b);
void kurang(int a, int b);

void main() {
tambah(10, 12);
tambah(100, 200);
kurang(30, 45);
kurang(200, 125);
getch();
}

void tambah(int a, int b) {
cout << a + b << endl;
}

void kurang(int a, int b) {
cout << a - b << endl;
}

Output:

22
300
-15
75

6. Default parameter values

One of the specialties of C++ is the ability to use default values ​​of function parameters. Parameters that have default values ​​can later be omitted from the function call.

Example:

#include <iostream.h>
#include <conio.h>

void hello(int jum=1); // Prototipe fungsi

void main() {
clrscr();
hello();
hello(3);
getch();
}

void hello(int jum) {
for (int i = 0; i < jum; i ++) {
cout << " C++ " << endl;
}
cout << " Selesai " << endl;
}

Output:

C++
Done
C++
C++
C++
Done

7. Pass By Value

Passing parameters by value . By default, the arguments we define in a function are pass by value, which means they will be passed into the function and will not change after the function is executed. Consider the following example:

Example:

#include <iostream.h>
#include <conio.h>

void perkalian(int a, int b, int c);

void main() {
int a = 10, b = 30, c = 0;
cout << "\nNilai c SEBELUM fungsi perkalian dipanggil : " << c;
perkalian(a, b, c);
cout << "\nNilai c SETELAH fungsi perkalian dipanggil : " << c;
getch();
}

void perkalian(int a, int b, int c) {
c = a * b;
cout << "\nNilai c DALAM fungsi perkalian " << c;
}

Output:

Nilai c SEBELUM fungsi perkalian dipanggil : 0
Nilai c DALAM fungsi perkalian 300
Nilai c SETELAH fungsi perkalian dipanggil : 0

8. Pass By Reference

Passing parameters by reference. Unlike pass by value which will not affect the parameter value after the function is executed, pass by reference will affect the value after the function is executed. To pass parameters by reference, add an ampersand ('&') in front of the parameter name. Here is the previous example that has been changed to pass by reference:

Example:

#include <iostream.h>
#include <conio.h>

void perkalian(int a, int b, int &c);

void main() {
int a = 10, b = 30, c = 0;
cout << "\nNilai c SEBELUM fungsi perkalian dipanggil : " << c;
perkalian(a, b, c);
cout << "\nNilai c SETELAH fungsi perkalian dipanggil : " << c;
getch();
}

void perkalian(int a, int b, int &c) {
c = a * b;
cout << "\nNilai c DALAM fungsi perkalian " << c;
}

Output:

N
ilai c SEBELUM fungsi perkalian dipanggil : 0
Nilai c DALAM fungsi perkalian 300
Nilai c SETELAH fungsi perkalian dipanggil : 300

9. Functions with Return Values

When we create a function, we often want it to perform a process and return a certain value when it is called. We can use the return keyword in a function to return a value when the function is called.

Declaration format for a function that returns a value:

tipe nama_fungsi(daftar_parameter);

Every function called in the program must be defined first, which can be located anywhere. Especially for functions provided by the system, the actual definition is already in the library called the header file, for example #include

Example1:

#include <iostream.h>
#include <conio.h>

int tambahkan(int a, int b);
long kuadrat(long a);

void main() {
int a = 10, b = 30,
c = 0; a = kuadrat(a);
b = kuadrat(b);
c = tambahkan(a, b);
cout << "nilai c sekarang = " << c;
getch();
}

int tambahkan(int a, int b) {
return a + b;
}

long kuadrat(long a) {
return a * a;
}

Output:

current value of c = 1000

Examples 2:

A function with a return value is a function that provides a return value to the function caller, for example:

//prototipe fungsi

long kuadrat (long x);
----------------------

//definisi fungsi
long kuadrat (long x)
{

return(x * x);

}

The return statement inside a function is used to return a function value. In the example above, the square() function returns a square value of the argument.

Source Code:

#include <iostream.h>
#include <conio.h>
#include <iomanip.h>

/**
*www.bundet.com
*Contoh C++ Fungsi Nilai Balik
*Fungsi Kuadrat
*/

long kuadrat(long l); //prototipe fungsi

void main()
{
 clrscr();
 for (long bil = 200; bil < 2000; bil+=200)
 cout << setw(8) << bil << setw(8) << kuadrat(bil) << endl;

 getch();
}

//definisi fungsi
long kuadrat(long l)
{
 return(l*l);
}

Output:


C++ Example of Calculating Squares With Return Value Function

10. Functions without Return Value

Sometimes a function does not need to have a return value. For example, a function that is only intended to display a description, in a function like this, the return value type of the function required is void.

Declaration format for functions that do not return a value:

void nama_fungsi(daftar_parameter);

Example:

void tampilkan_judul()
{
cout << "PT. MOJA MAJU" <
cout << "JL. Buntu No.xx" <
cout << "bundet.com" <
}

The example above is a function without a return value because there is no return statement, considering that the function does not have a return value, but the use of an explicit return statement is also permitted, in this case it is used as a formality, for example:

void tampilkan_judul()
{
cout << "PT. MOJA MAJU" <
cout << "JL. Buntu No.xx" <
cout << "bundet.com" <
return;
}

Example of a function program without a return value:

Program:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Fungsi Tanpa Nilai Balik
*/

void tampilkan_judul();
void line();

//fungsi utama
void main()
{
clrscr();
tampilkan_judul();
line();
getch();
}

//definisi fungsi
void line()
{
cout<<"======================================="<<endl;
}

void tampilkan_judul()
{
cout<<"GATEWAN"<<endl;
cout<<"alamat : bundet.com"<<endl;
cout<<"Yogyakarta"<<endl;

return;
}

11. Variable Scope

The scope of a variable determines the existence of a particular variable in a function. There are variables that are only known in a function and are not known in other functions. However, there are also variables that can be accessed by all functions.

a. Local Variables

Local variables are variables declared inside a function and are only recognized within the function in question. Local variables can also be called automatic variables. Consider the following example:

Example:

#include <iostream.h>
#include <conio.h>

void lokal();

void main() {
int a = 25;
cout << "\nNilai a dalam fungsi main = " << a;
lokal();
cout << "\nNilai a dalam fungsi main = " << a;
getch();
}

void lokal() {
int a=70;
cout << "\nNilai a dalam fungsi lokal = " << a;
}

Output:

Nilai a dalam fungsi main = 25
Nilai a dalam fungsi lokal = 70
Nilai a dalam fungsi main = 25

b. External Variables

External variables are variables declared outside the function and are global so they can be used together without having to be declared repeatedly. Consider the following example:

Example:

#include <iostream.h>
#include <conio.h>

int a = 77;
void lokal();

void main() {
a = 25; cout << "\nNilai a dalam fungsi main = " << a;
lokal();
cout << "\nNilai a dalam fungsi main = " << a;
getch();
}

void lokal() {
a+=7;
cout << "\nNilai a dalam fungsi lokal = " << a;
}

Output:

Nilai a dalam fungsi main = 25
Nilai a dalam fungsi lokal = 32
Nilai a dalam fungsi main = 32

c. Static Variables

Static variables can be local variables or external variables. These static variables have properties including:

  • If a static variable is local, then the variable is only known by the function where the variable is declared.
  • If a static variable is external, then the variable can be used by all functions located in the same file.
  • If a static variable value is not given, it will automatically be assigned a value of zero.

Example:

#include <iostream.h>
#include <conio.h>

void saya_ingat();

void main(){
int mana = 50;
clrscr();
saya_ingat();
saya_ingat();
saya_ingat();
cout << " main() : mana = " << mana << endl;
getch();
}

void saya_ingat() {
static int mana = 77; mana ++;
cout << " Saya_ingat () : mana = " << mana << endl;
}

Output:

Saya_ingat () : mana = 78
Saya_ingat () : mana = 79
Saya_ingat () : mana = 80
main() : mana = 50

12. Function Overloading

Function overloading means defining multiple functions with the same name but with different parameters.

Example:

#include <iostream.h>
#include <conio.h>

int kuadrat(int angka);
long kuadrat(long angka);
float kuadrat(float angka);

void main() {
int a = 200;
float b = 50.56;
long c = 120;
cout << a << " dikuadratkan menjadi " << kuadrat(a) << endl;
cout << b << " dikuadratkan menjadi " << kuadrat(b) << endl;
cout << c << " dikuadratkan menjadi " << kuadrat(c) << endl;
getch();
}

int kuadrat(int angka){
return (angka * angka);
}

long kuadrat(long angka) {
return (angka * angka);
}

float kuadrat(float angka) {
return (angka * angka);
}

Output:

200 dikuadratkan menjadi 40000
50.56 dikuadratkan menjadi 2556.31
120 dikuadratkan menjadi 14400

If you have managed to understand it and want to try with a slightly more complex case, then there is nothing wrong if you try to start by understanding the algorithm in  the Example Program for Calculating Student Transcript Grades .

Source:

System Programming Practical Module. STMIK El Rahma Yogyakarta. By  Eding Muh. Saprudin, S.Kom

Other Version Notes

Functions in C++ play a very important role. This is because a program in C++ is actually a collection of functions. The functions that are already available or that we create ourselves will be called in the main function, namely main(). Like all programming languages, C++ provides built-in functions that can be accessed by first calling the header file at the beginning of the program we create. C++ also provides facilities for creating your own functions (user-defined functions). In this sub-chapter we will learn how to create your own functions.


Getting to know FUNCTIONS IN C++ 

There are two types of functions, namely functions that do not return a value and functions that return a value.

Functions that do not return a value

This function is created with the type void. In VB or Pascal, this function is known as a procedure. Consider the following example 9.16.

Example 9.16. Function without returning a value

#include <iostream> using namespace std;

// Membuat fungsi cetak angka void CetakAngka() {   for (int C=0; C<10; C++) {     cout<<C+1<<endl;
  }
}

// Fungsi utama dalam program C++ int main() {

  // Memanggil fungsi CetakAngka
  CetakAngka();
   return 0; }

In this example we create a function named CetakAngka with a void type so it does not return a value. Note how to declare the function. The function will run until the end of the code in the function.

Functions that return values

This function will return a value to be used in another part of the program. To define a function of this type, we do not use void, but directly the data type of the value that will be returned by the function. Consider the following example 9.17.

Example 9.17. Function with return value

#include <iostream>

using namespace std;

// Membuat fungsi dengan nilai pengembalian tipe char char* NilaiChar() {
  return "Ini nilai yang akan dikembalikan";
}

// Fungsi utama int main() {
  // Memanggil dan menampilkan hasil fungsi   cout<< NilaiChar();

  return 0; }

In this type of function, we need a return statement to indicate the part whose value will be returned. In the example above, the data type of the value to be returned is char. The char form with the * sign indicates that the variable NilaiChar may contain more than one letter and will be stored/printed as when we entered its contents.

2. Use of Parameters in Functions

As in VB and Java, functions in C++ also allow parameters or arguments to be used to pass input or hold output from the function. Consider the following examples.

Example 9.18. Function with input parameters

#include <iostream> using namespace std;

// Membuat fungsi dengan parameter input int Kuadrat(int X) {   int hasil;   hasil = X * X;   return hasil;
}  int main() {   int Bil, HASIL;
  cout<<"Masukkan sebuah bilangan bulat : ";    cin>>Bil;
  HASIL = Kuadrat(Bil);  //memanggil fungsi kuadrat   cout<<"Kuadrat dari bilangan "<<Bil<<" adalah :
"<<HASIL;    return 0; }

The function in example 9.18 is Square. This function requires one input variable (in the example called X). In the main() function, the variable Bil is the variable used to store the value used as a parameter in the Square function when it is called.

Example 9.19. Function with input and output parameters

#include <iostream> using namespace std;

// Membuat fungsi dengan parameter input int Kuadrat(int X, int *hasil) {
  *hasil = X * X;   return *hasil;
}  int main() {   int Bil, HASIL;
  cout<<"Masukkan sebuah bilangan bulat : ";    cin>>Bil;
  // Menampilkan nilai setelah diproses di dalam fungsi   cout<<"Kuadrat dari bilanga "<<Bil<<" adalah :
"<<Kuadrat(Bil, &HASIL);
   return 0; }

Example 9.19 is an extension of Example 9.18. In the Quadrat function we add an output parameter, namely result. The output parameter must be passed based on its memory address (namely result), so it must use a pointer (see the * sign before the result variable. Likewise, the way the function is called, the input and output parameters must be mentioned. The output parameter that stores the calculation result must be given the prefix &.

Question 1

NAUVAL S Oct 2, 2015, 08:11:00 Thanks, but there are still some errors in the coding (*tried in Dev C++) Example of a correct program (revised):

#include
#include
#include

using namespace std;
//prototipe fungsi gatewan.com
void tampilkan_judul();
void line();

//fungsi utama
int main(){
system("cls");
tampilkan_judul();
line();
getch();
}

//definisi fungsi
void line(){
cout<<"=======================================\n";
}

void tampilkan_judul() {
cout<<"GATEWAN"<

ALDIAN SAPUTRA Feb 28 2016, 02:40:00 That's right bro, it's still running, why do we use Borland C++

IBNU ROKHMAN 3 Dec 2015, 22:38:00 Sorry WAWAN REALLY,, sir using Borland C++ application,,, If I use DEV-C++,,, it means the code is a little different,,,  @NAUVAL S,  Sorry in advance, As far as I know if we use "using namespace std;" it will definitely work for all codes,,,, using namespace std; if I'm not mistaken is a command that ignores errors,,, thank you

Response 1

Hii Nauval S, thanks for the addition, good job  😃 Using Dev C++ editor+compiler huh? It seems we have different editor+compiler, because I use Borland C++ and until now the code above can still be run... thanks

Question 2

MUHAMMAD MUHAFIZHIN 8 Mar 2016, 11:59:00 the explanation is lacking

ASHIF F. RIADY Apr 3, 2016, 15:11:00 What compiler do you use for this app, bro? Why do I find that many of the codes I copied to the codeblock are not declared yet?

ASHIF F. RIADY3 Apr 2016, 17:55:00 I can do it, sir, I'm a newbie, I'm still confused, after fiddling with it, I finally can, my suggestion is that it's better to include what compiler to use, because for a layman, copying the program to the compiler doesn't necessarily mean the program will run straight away. It seems like what I experienced, I used the codeblock compiler, I copied the program, but there are some things that need to be fixed again, such as the library, if in the codeblock when using the #include preprocessor on the library, it doesn't need to be added (.h) and after the program works I just understand the return function and the void function. Thank you, sir, your knowledge is very helpful for a layman like me. I attach a program that works on the codeblock compiler

#include
#include
#include

/**
*www.bundet.com
*Contoh C++ Fungsi Nilai Balik
*Fungsi Kuadrat
*/

long kuadrat(long l); //prototipe fungsi

int main()
{
void clrscr();
for (long bil = 200; bil < 2000; bil+=200)
std::cout << std::setw(8) << bil << std::setw(8) << kuadrat(bil) << std::endl;
getch();

}

//definisi fungsi
long kuadrat(long l)
{
return(l*3);
}

Sorry, it was wrong earlier, it should have returned (1 1) for square, (1 1 1) for power 3, so it's not (1 3), when the return parameter is not tampered with, aka fresh copy paste, the program works normally, but when the return parameter is changed to (1 3) it becomes a multiplication of the long function, when it is reversed to (1 1) it's the same, I don't really understand what's wrong with the program or the compiler

Response 2

Is there anything unclear, bro? Please ask if you don't understand which part of the program above... thank you.

the code above uses Borland C++, Mr. ASHIF F. RIADY. Okay, Mr. ASHIF F. RIADY, Good job, congratulations!!, and may you always be successful in your studies!

Question 3

ARMITA IMA FRADILA Jan 2 2017, 13:37:00 Why is there an error in example one?

ROBBY ALVIAN JAYA MULIA Aug 3, 2017, 16:53:00 Thanks bro, this website is very useful if you have an assignment. Success bro!!

Response 3

I just tried it, sis, and it still works, here's the proof: enter image description here

If I may, Miss ARMITA IMA FRADILA, what compiler do you use?

Hi ROBBY ALVIAN JAYA MULIA, you're welcome, good job!

Understanding Arguments in C++

Function arguments are default values ​​that will be included when calling the function. In the example below, the print function has an argument named jum of type int, so when calling the print function, it must be accompanied by the number of arguments that will be given when the function is called.

cetak(10);

output:


C++ Argumen

Program:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Contoh Penggunaan Argumen
*/

void cetak (int jum);

void main()
{
 clrscr();
 cetak(10);
 getch();
}

void cetak (int jum)
{
 for(int i=1; i<=jum;i++)
 cout<<i<<". bundet.com ini tercetak 10 kali"<<endl;
}

Next we will try to print text in the center of the screen or at certain coordinates.

output:


C++ Print Text in the Middle

Program:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Cetak Text di Tengah Layar
*/

void hapus()
{
 clrscr();
}

void henti()
{
 getch();
}

//prototipe fungsi mencetak pada koordinat tertentu
void cetak(int klm, int brs, char *teks);

//prototipe fungsi mencetak pada tengah layar

void cetakc(int brs, char *teks);

void main()
{
 hapus();
 cetakc(1,"www.bundet.com ADA DITENGAH LAYAR");
 cetakc(2,"==========================");
 cetak(3,4,"Tulisan ini tercetak pada baris 4 kolom 3");
 henti();
}

//definisi fungsi

void cetak(int klm, int brs, char *teks)
{
gotoxy(klm,brs); cout<<teks;
}

void cetakc(int brs, char*teks)
{
gotoxy(40-strlen(teks)/2,brs);cout<<teks;
}

Hope this is useful & happy learning!

Understanding Parameters / Conditions in C++

This expression is very similar, as you, when determining a formula in a Microsoft Excel worksheet. But this time we do it on the C++ editor sheet. In the case studies that we usually talk about, we usually use branching to determine a certain condition, but this time we do it differently, for more details please see the code line below:


C++ Conditions / Parameters With Other Expressions

Source Code:

# include<iostream.h>
# include<conio.h>

/**
*bundet.com
*c++ parameter/kondisi ekspresi lain
*/

void main (){
 int nilai = 0;

 cout << "masukkan nilai : ";
 cin >> nilai;

cout << ( ( nilai < 45 ) ? 'E' : ((nilai >= 45 && nilai < 55 ) ? 'D' : (nilai >= 55 && nilai < 65 ? 'C' : (nilai >= 65 && nilai < 75 ? 'B' : 'A')) ) ) ;

 getch () ;
}

Hope this is useful & happy learning!

Method aka C++ Function with Multi Parameters

Program:

#include <iostream.h>
#include <conio.h>

/*
*Wawan Beneran
*membuat fungsi dengan multi parameter
*/

void main(){
profil("wawan","www",17);//kalian bisa mengeditnya di sini

getch();
}

void profil(char*nama, char*alamat, int usia=17){

cout<<"Nama : "<<nama<<endl;
cout<<"Alamat : "<<alamat<<endl;
cout<<"Usia : "<<usia<<endl;

if(usia>=17){
cout<<"Usia"<<usia<<"th"<<endl;
}
else{
cout<<"Maaf usia minimal peserta adalah 17 th"<<endl;
}
}

Output:

C++ Function Template Usage

In programming, especially those that are highly dependent on variable types, we are often troubled by having to create functions that function the same but with different variable types. For that, a new keyword, template, was introduced in C++. By using templates, we can create a function that can support all types of variables, not limited to variables defined by C/C++ keywords but also supports use for future variable types. The use of templates is not limited to functions but also includes classes (including structs, unions). In general, the use of templates can be divided into 2, namely templates in functions (function templates) and templates in Classes (class templates). Okay, I think we'll just discuss the use of templates.


C++ Template Usage

1. Function Template 

First of all, let's discuss the function template. For that, let's look at the following example.

template <class tipe> void swap(tipe &a,tipe &b)
{  tipe c;  c = a;  a = b;  b = c; }

In the example above there is a swap function (exchanging 2 variables) using a template. The function call is done like a function call without a template. For that, let's pay attention to the command excerpt to use the swap function.

Example template with instances of type int;

void main(void)
{  int a,b;  a = 10;  b = 20;  swap(a,b);
 cout << a << " " << b << endl;
}

Example template with float type instances

void main(void)
{  float a,b;  a = 10.0;  b = 20.0;  swap(a,b);
 cout << a << " " << b << endl;
}

Example template with struct tTes instance

struct tTes {  int a,b;
};
void main(void)
{  tTes a,b;

 a.a = 10;
 a.b = 20;
 b.a = 30;
 b.b = 40;   swap(a,b);
 cout << a.a << " " << a.b << " " << b.a << " " << b.b;
}

As can be seen, by using a template we have saved time writing functions. In the swap function above, it is also possible to swap 2 classes.

In the example above, the function will not work if the variables being swapped are of different types. Even though the relationship is quite close. You cannot swap an int type (16bit) with a short type (16 bit). This is related to the template declaration in the swap function.

template <class tipe> void swap(tipe &a,tipe &b)

In the swap function declaration, it can be seen that the formal parameter a is the same as the formal parameter b. Therefore, the type of the actual parameter must also be the same. For the example of the swap function above, you should not use type-casting to solve the problem above. Given that the swap function above is sent by reference. (Which in sending a function using a reference is related to a pointer). Of course, the size of the variable is very important because we have changed the size of the variable (type casting) unexpected results can occur. Although sometimes it gives the correct results. Unless the size of the two types of variables is exactly the same, you can use type--casting in this case.

To define more than one type in a template you can use a comma as a separator, for example:

Template with 2 template types <class type1,class type2>

2. Overloading Template Function

If at any time there is a variable that must be treated specially to exchange it you can overload a template function. For example: suppose if you want to exchange 2 float variables without having to consider negative or positive. You just create an additional function with a float variable. So when run the compiler will prioritize first on functions that have formal parameters and actual parameters with the same type. Only then if not found then the compiler will create an instance of the template function that you have created. For more details let's see the following source code example.

#include <iostream.h>

template <class Tipe> void swap(Tipe &a,Tipe &b)
{  Tipe tmp;  tmp = a;  a = b;  b = tmp;
}
void swap(float &a,float &b)
{  float c;
 a = (a < 0.00)?-a:a;  b = (b < 0.00)?-b:b;  c = a;  a = b;  b = c;
}

void main(void)
{  float a,b;  a = -10.0;  b = 20.0;  swap(a,b);  cout << a << " " << b;
}

3. Class Template 

The next type of template is Class template. Class Template, not only applies to defining templates in classes but also applies to defining structs and unions. The way to define is the same as Function template, the only difference is in how to create an instance of the class template. For more details, let's look at an example of defining a Class Template.

Defining a Class Template in a CMyTemplate class

template <class MyTipe> class CMyTemplate
{  protected :   MyTipe m_a,m_b;
 public    :
 void Done(void)
{
 memset(&m_a,0,sizeof(MyTipe));  // pendeklarasian method
}  // didalam kelas

};

//pendeklarasian methos diluar kelas template <class MyTipe>
void CMyTemplate<MyTipe>::Init(MyTipe a,MyTipe b)
{  m_a = a;  m_b = b;
}

Defining a Class Template on a struct tMyStruct

template <class MyTipe> struct tMyStruct {
 MyTipe a,b; };

Defining a Class Template on a union _MyUnion

template <class MyTipe> union _MyUnion {  MyTipe a;  int b; };

What needs to be noted from the example above, among other things, is the difference between defining a method inside or outside a class.

To use a template class, we must first define an instance of the template to be created. To define an instance of a template class, we can do this by writing the data type of the instance enclosed by the "<" ,">" signs. Example:

void main(void)
{
 CMyTemplate<short> a; // membuat instance CMyTemplate dengan tipe short   tMystruct<short> b;  // membuat instance tMyStruct dengan tipe short
 _MyUnion<float> c;  // membuat instance _MyUnion dengan tipe float
}

In the CMyTemplate instance declared with the short data type, MyType (in the class definition) will be short. This means that the variables m_a and m_b will be of type short as well as in struct and union. To define more than 1 type in a class template, you can do the same as Function Template, namely by using a comma as a separator.

Example:

template <class MyTipe1,class MyTipe2> class CMyTemplate
{  protected :   MyTipe1 m_a
  MyTipe2 m_b;
 public    :   void Init(MyTipe1 a,MyTipe2 b)
  {    m_a = a;    m_b = b;
  }
};

To create an instance, just add a comma. Example:

void main(void)
{
 CMyTemplate<short,float> a;
}

So now in Object a , Variable m_a will be of type short while in variable m_b it will be of type float.

Well, I think that's all for the template explanation this time, hopefully it can be useful. For greetings, questions, criticisms and others, just send them to my email address.

Reference:

By:

Source:

  • IlmuKomputer.Com

Post a Comment

Previous Next

نموذج الاتصال