Вы находитесь на странице: 1из 33

C++

Programming
Language
--------------------------------------------------------------------------------------------------------------------------------------

(Part II)

MOHD. UZIR KAMALUDDIN


Faculty of Electrical Engineering
Science and Technology Complex
University Teknologi MARA (UiTM)
40450 SHAH ALAM
Phone 603-5543 5052 Fax 603-5543 5077

Copyright 2015 by Mohd. Uzir


Third Edition Mac 2015
All rights reserved. No part of these notes may be used or reproduced in any manner whatsoever without the permission of the
author.
This book is a work the lecturer while teaching the course on C++ programming language, as to provide a guide for the
students in understanding the subject matter. It is hoped that this work will benefit the students.
Any mistakes or shortcomings in these notes are due to the error of the author, and all that is correct and true solely are due to
ALLAH Subhana huWa Taala.

ISBN: not available


First Edition: Jan 2010

Contents
Contents................................................................................................................................................................................. 3
ARRAYS ................................................................................................................................................................................. 5
One-Dimensional Array (Single-Subscript Array) ....................................................................................................... 5
Two-Dimensional Array (Two-Subscript Array) ......................................................................................................... 6
Pointers & Arrays ............................................................................................................................................................. 7
Arrays and Functions ....................................................................................................................................................... 8
FILES ....................................................................................................................................................................................10
Input/Output With Files ...............................................................................................................................................10
Open a file........................................................................................................................................................................10
Closing a file ....................................................................................................................................................................11
Text files ...........................................................................................................................................................................12
Checking state flags ........................................................................................................................................................13
STRUCTURES ....................................................................................................................................................................14
Structures..........................................................................................................................................................................14
Pointers & Structures .....................................................................................................................................................16
Structures and Functions ...............................................................................................................................................17
Enumerated Types..........................................................................................................................................................17
Union Types ....................................................................................................................................................................18
OBJECT ORIENTED PROGRAMMING (OOP) .....................................................................................................20
Benefits of OOP .............................................................................................................................................................20
OOP Basics: Classes and Instances .............................................................................................................................21
Class Definition...............................................................................................................................................................21
Creating Instances of a Class ........................................................................................................................................21
Dot (.) Operator ..............................................................................................................................................................22
Data Members (Variables) .............................................................................................................................................22
Member Functions .........................................................................................................................................................22
Putting them Together: An OOP Example ...............................................................................................................23
Constructors ....................................................................................................................................................................23
Default Constructor .......................................................................................................................................................25
Destructor ........................................................................................................................................................................25
"public" vs. "private" Access Control Modifiers .......................................................................................................25
Information Hiding and Encapsulation ......................................................................................................................25
Getters and Setters..........................................................................................................................................................26
Inheritance .......................................................................................................................................................................26
Forms of Inheritance......................................................................................................................................................26
Constructor and inheritance..........................................................................................................................................28
Virtual Base Class............................................................................................................................................................29
Polymorphism, Virtual Functions and Abstract Class ..............................................................................................30
Pointer of base class .......................................................................................................................................................30
Using Type Casts with Base Class Pointers ................................................................................................................31

Virtual Function and Polymorphism ...........................................................................................................................31


Pure Virtual Function and Abstract Class ..................................................................................................................32

ARRAYS
An array is a group of memory locations related by the fact that they all have the same name and the
same type. All the elements of an array occupy a set of contiguous memory locations. To refer to a
particular location or element in the array, the name and the position number of the particular
element is specified. The position number is contained within square brackets, called a subscript or
index. An array allows the programmer to store and work with multiple values of the same data
type.
One-Dimensional Array (Single-Subscript Array)
An array is defined by int x[8]; which reserves 8 elements of type integer in array x. The individual
elements would be x[0], x[1],x[7]. Array
name: x, type of data: integer, size of array: 8
An array may be initialized when they are
declared.
Example to show how an array is initialized using for loop.
#include<iostream>
using namespace std;
int main (){ int n[10], i;
for (i=0; i<10; i++) { n[i] = 0; } /* all elements equals zero */
for (i=0; i<10; i++) { cout << "\n "<< i <<"\t" << n[i]; } /*printing array elements */ }

Example to show how an array is initialized with an initializer list


#include<iostream>
using namespace std;
int main (){
int i, n[10] = { 23, 45, 34, 21, 56, 76, 44, 77, 56, 11 };
for (i=0; i<10; i++) { cout << "\n "<< i <<"\t" << n[i]; } }

If the initializers are fewer than the elements in the array, the remaining elements are initialized to
zero.
int n[10] = { 12, 43, }; or int n[10] = { 0 };
If the array size is omitted, the number of elements in the array will be the number of elements in
the initializer list, for example int n[ ] = { 1, 2, 3, 4, 5 } would create a 5-element array.
Example shows how to read integer values from user, and stop reading when user enters -1.
#include<iostream>
using namespace std;
int main (){
int n[100], i;
cout<<"\nPls enter integer values: (-1 to end) "<<endl;
for (i=0; i<100; i++){cin>>n[i]; /* reading until -1 is read */
if(n[i]==-1) break;}
cout<<"\nThe array entered:\n";
for (i=0; i<100; i++) { if(n[i]==-1) break;
cout << "\n "<< i <<"\t" << n[i]; } /*printing array elements */

Individual array elements are processed like any other type of variable.

Example: Finding the highest value in a numeric array.


const int SIZE=10;
int numbers[SIZE]={15,6,3,11,22,4,0,1,9,12};
int count, highest;
highest=numbers[0];
for (count=1; count<SIZE; count++){
if (numbers[count]>highest)
highest=numbers[count]; }

#include <iostream>
using namespace std;
int main ()
{ int data[ ] = {16, 2, 77, 40, 12, 71};
int n, result=0;
for ( n=0 ; n<6 ; ++n )
{ result += data[n]; }
cout << result; //sum
return 0; }

//Graphing array element values with histograms


#include<iostream>
using namespace std;
main()
{ int n [10] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
int i, j;
cout << "\n"<< " Element"<< " Value"<< " Histogram"<<"\n";
for (i=0; i<10; i++) {
cout << " "<< i<<" "<<" "<< n[i]<<" ";
for (j=1; j<= n[i]; j++) {
cout << ( "*" ); }
cout << "\n";
} }

Using arrays to store and manipulate strings


A character array can be initialized using a string literal eg. char string[ ] = first;
The string first contains 5 characters and a special termination character called null character \0;
that gives a total of 6 elements.
Another way to initialize: char string [ ] = { f, i, r, s, t, \0 };
#include<iostream>
using namespace std;
main()
{ int n,i=0,m[8]={0};
cout<<"Pls enter a decimal number : ";
cin >> n;
if (n>0) { cout<<n<<" Decimal = ";
while(n>0){ m[i]=n%2;
n=n/2;
i++; }
for(i=7;i>=0;i--) cout<<m[i];
cout<<" in binary."<<endl; }
else cout<<" --Pls enter number bigger than zero."<<endl;

CHECK
1. The arrays num1 and num2
each hold 25 integer elements.
}
Write a program that copies the
values in num1 to num2.
2. Write a program that accepts 10 integers from the user and stores them in an array. The
program then displays how many numbers in the array that is greater than 25.
3. Create an array that stores as strings the Roman numeral equivalent of numbers between 1 and
15. Write a program that displays the Roman equivalent of decimal numbers between 1 and 15
using the array content. The program should loop continuously until the user enters 0.
Two-Dimensional Array (Two-Subscript Array)
Arrays can have multiple subscripts. Common use is to represent tables of values consisting of
information arranged in rows and columns i.e. matrix which has two subscripts.
A two-dimensional array can be viewed as a table, which will have x number of rows and y number
of columns. A 2-dimensional array a, which contains three rows and four columns a[3][4] can be
shown as below:

COMPUTER PROGRAMMING (C++)

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing a two dimensional array
example; int b[2][2] = { {1, 2}, {3, 4} };
or int n[2][3] = { {1, 2, 3}, {4, 5, 6} };
/* Read and display a matrix */
#include <iostream>
using namespace std;
int main()
{ int x, y;
int array[8][8]; // Declares an array like a chessboard
for ( x = 0; x < 8; x++ ) {
for ( y = 0; y < 8; y++ )
array[x][y] = x * y; } // Set each element to a value
cout<<"Array Indices:\n";
for ( x = 0; x < 8; x++ ) {
for ( y = 0; y < 8; y++ )
cout<<"["<<x<<"]["<<y<<"]="<< array[x][y] <<" ";
cout<<"\n"; } }

#include <iostream>
using namespace std;
main()
{ int n; int i, j; int m1[10][10];
cout << "Input the matrix size (max 10): ";
cin >> n;
cout << "Input the matrix by row:\n";
for (i=0; i<n; i=i+1)
for (j=0; j<n; j=j+1)cin >> m1[i][j];
cout << "The matrix is:\n";
for (i=0; i<n; i=i+1)
{for (j=0; j<n; j=j+1)cout << m1[i][j]<<" ";
cout << "\n";} }

Pointers & Arrays


Pointers and arrays are very closely linked in C++. Think of array elements arranged in consecutive
memory locations.
To access a specific element in an array, the arrays name together with its subscript or index is used.
The array name provides the address of its first cell, and the index provides the offset from this first
cell. Consider the following:
int a[10], x;
int *pa;
pa = &a[0]; /* pa pointer to address of a[0] the same as doing pa = a */
x = *pa;
/* x = contents of pa (a[0] in this case) */

To get somewhere in the array using a pointer, do:


pa + i = a[i]
WARNING: There is no bound checking of arrays and pointers so it can easily go beyond array
memory and overwrite other things.
For example we can just type pa = a; instead of pa = &a[0] and a[i] can be written as *(a + i)
i.e. &a[i] = a + i.
Pointer addressing can also be expressed like this: pa[i] = *(pa + i).
However pointers and arrays are different:

A pointer is a variable. This is acceptable, pa = a and pa++.

An array is not a variable. a = pa and a++ ARE ILLEGAL statements.


Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 7 of 33

#include <iostream>
using namespace std;
main()
{ int lucky_no[ ] = {1, 3, 5, 7};
int *ptr;
ptr = lucky_no; /*ptr have the address of first element in array*/
cout << "Number in first cell:"<<*ptr<<endl;
ptr = &lucky_no[0]; /*ptr have the address of first element in array*/
cout << "Number in first cell:"<<*ptr<<endl;
ptr = &lucky_no[2]; /*ptr have the address of third element in array*/
cout << "Number in third cell:"<<*ptr<<endl;
ptr = &lucky_no[1]; /*ptr have the address of second element in array*/
cout << "Number in second cell:"<<*ptr<<endl; }

Arrays and Functions


When an array is passed to a function what is actually passed is its initial elements location in
memory.
//Example shows the data in an array is passed to
//a function.
#include <iostream>
using namespace std;
void print_sq(int x);
main( )
{ int i;
int base[5] = {3, 7, 2, 4, 5};
for (i=0; i<5; i++) print_sq (base[i]); }
void print_sq (int x)
{ cout << x*x<<" "; }

//Example shows the name of array is passed to a function. The


//function can have access to the whole array.
#include <iostream>
using namespace std;
float average (int x[ ]);
main( )
{ float ave;
int base[5] = {3, 7, 2 ,4, 5};
ave = average (base);
cout << ave; }
float average (int x[ ])
{ int i, sum;
for (i=0; i<5; i++) sum += x[i];
return (sum/5.0); }

/*Example shows the whole array is passed to a function and the


function manipulate the data in the array. Thus there is no need to
return any values.*/
#include <iostream>
using namespace std;
void mult (int x[ ]);
main( )
{ int i, base[5] = {3, 7, 2 ,4, 5};
mult (base);
for (i=0; i<5; i++) cout << base[i]<<" "; }
void mult (int x[ ])
{ int i;
for (i=0; i<5; i++)
x[i] *= 2; }

COMPUTER PROGRAMMING (C++)

This program reads integer data entered from keyboard until value 0 is entered or when 10 numbers has been
entered, then the number of items entered and its sum is displayed.
#include <iostream>
using namespace std;
int sum ( int a[ ], int n );
main( )
{ int b[10], x, m=0;
while (m < 10)
{ cin>>b[m];
m++;
/*make m to show last item in array b*/
if (b[m-1]==0) break; }
m--;
cout << m<<" items input\n";
if (m>=0) { x = sum (b, m);
cout << "sum = "<< x; } }
int sum (int a[ ], int n)
{ int partial_sum =0, i;
for ( i=0; i<=n; i++) partial_sum += a[i];
return partial_sum; }

CHECK
1. Write a program that stores in an array 20 random numbers between 100 and 1000 generated by
random number generator rand(), and then display the sum and average of the 20 numbers.
2. Write a program that will produce a table of values stored in an array of the equation:

y 2 e0.1t Sin 0.5t


where t varies between 0 to 60. The size of t increment is to be entered by the user.
3. Create an array that holds the following floating point numbers:
27.5, 87.0, 13.4, 39.9, 53.8, 47.7, 29.2, 10.5, 74.5, 63.2 and then find the standard deviation s of the
numbers using the formula:-

d12 d 2 2 ... dm 2
where d1, d2,..dm are deviation about the mean x .
m
and deviation di = (xi- x ) where i=1, 2, m and the mean x =(x1+x2++xm)/m.
s

4. Write a program that simulates a lottery. The program should have an array of 5 integers named
winDigits filled with a randomly generated number in the range of 0 through 9 for each element
in the array. The program should ask the user to enter 5 digits and stored in an array named
player. The program then compares the corresponding elements in the two arrays and count
how many digits match and display it. The program must not accept input that is less than 0 or
greater than 9.

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 9 of 33

FILES
Input/Output With Files
Sometimes the output that is produced from a program is required to be stored on the hard disk for
further viewing or maybe the input data is already stored in files and need to be read by a program
for further processing. C++ provides the following classes to perform output and input of characters
to/from files.
ofstream:
Stream class to write on files
ifstream:
Stream class to read from files
fstream:
Stream class to both read and write from/to files.
There are two file types:
binary files contain sequence of characters, each addressable by the programmer as an offset from
a fixed position in the file.
Text files contains sequence of characters that user enters, control or informational characters
from the system.
These classes are derived directly or indirectly from the classes ifstream and ofstream. We have
already used objects whose types were these classes: cin is an object of class ifstream and cout is an
object of class ofstream. Therefore, we have already been using classes that are related to our file
streams. And in fact, we can use our file streams the same way we are already used to use cin and
cout, with the only difference that we have to associate these streams with physical files. Let's see an
example:
// basic file operations
This program creates a file called example.txt and inserts
a sentence into it in the same way we are used to do with
cout, but using the file stream myfile instead.

#include <iostream>
#include <fstream>
using namespace std;
main ( ) {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this text to a file.\n";
myfile.close(); }

Open a file
The first operation generally performed on an object of one of these classes is to associate it to a real
file. This procedure is known as to open a file. An open file is represented within a program by a
stream object (an instantiation of one of these classes, in the previous example this was myfile) and
any input or output operation performed on this stream object will be applied to the physical file
associated to it.
In order to open a file with a stream object we use its member function open():open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that
string literals have) representing the name of the file to be opened, and mode is an optional
parameter with a combination of the following flags:
ios::in
ios::out
ios::binary
ios::ate
ios::app

Open for input operations.


Open for output operations.
Open in binary mode.
Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
All output operations are performed at the end of the file, appending the content to
the current content of the file. This flag can only be used in streams open for outputonly operations.

COMPUTER PROGRAMMING (C++)

ios::trunc

If the file opened for output operations already existed before, its previous
content is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open
the file example.bin in binary mode to add data we could do it by the following call to member
function open( ):
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Each one of the open( ) member functions of the classes ofstream, ifstream and fstream has a default
mode that is used if the file is opened without a second argument:
class
ofstream
ifstream
fstream

default mode parameter


ios::out
ios::in
ios::in | ios::out

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed,
even if a mode that does not include them is passed as second argument to the open( ) member
function.
The default value is only applied if the function is called without specifying any value for the mode
parameter. If the function is called with any value in that parameter the default mode is overridden,
not combined.
File streams opened in binary mode perform input and output operations independently of any
format considerations. Non-binary files are known as text files, and some translations may occur
due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream object is generally to open a file, these three
classes include a constructor that automatically calls the open( ) member function and has the exact
same parameters as this member. Therefore, we could also have declared the previous myfile object
and conducted the same opening operation in our previous example by writing:
ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);
Combining object construction and stream opening in a single statement. Both forms to open a file
are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to member is_open()
with no arguments. This member function returns a bool value of true in the case that indeed the
stream object is associated with an open file, or false otherwise:
if (myfile.is_open()) { /* ok, proceed with output */ }
Closing a file
When we are finished with our input and output operations on a file we shall close it so that its
resources become available again. In order to do that we have to call the stream's member function

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 11 of 33

close( ). This member function takes no parameters, and what it does is to flush the associated
buffers and close the file:
myfile.close();
Once this member function is called, the stream object can be used to open another file, and the file
is available again to be opened by other processes.
In case that an object is destructed while still associated with an open file, the destructor
automatically calls the member function close().
Opening a file for writing with prompt to user
whether it is successful or not. Sometimes the location
where the file to be opened is corrupted or not
available.

#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
main ( ) {
ofstream myfile;
myfile.open ("example.txt");
if (myfile.fail( ))
{ cout << "Output file opening failed.\n";
exit(1); }
myfile << "Writing this text to a file.\n";
myfile.close();
}

Text files
Text file streams are those where we do not include the ios::binary flag in their opening mode.
These files are designed to store text and thus all values that we input or output from/to them can
suffer some formatting transformations, which do not necessarily correspond to their literal binary
value.
Data output operations on text files are performed in the same way we operated with cout:
Data input from a file can also be performed in
the same way that we did with cin:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{ while ( myfile.good() )
{ getline (myfile,line);
cout << line << endl;
}
myfile.close(); }
else cout << "Unable to open file";
return 0;
}

// writing on a text file


#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

This last example reads a text file and prints out its content on the screen. Notice how we have used
a new member function, called good( ) that returns true in the case that the stream is ready for
input/output operations. We have created a while loop that finishes when indeed myfile.good( ) is
no longer true, which will happen either if the end of the file has been reached or if some other error
occurred.

COMPUTER PROGRAMMING (C++)

Checking state flags


In addition to good( ), which checks whether the stream is ready for input/output operations, other
member functions exist to check for specific states of a stream (all of them return a bool value):
bad()
Returns true if a reading or writing operation fails. For example in the case that we try to write to a
file that is not open for writing or if the device where we try to write has no space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens, like when
an alphabetical character is extracted when we are trying to read an integer number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of the previous
functions would return true.
In order to reset the state flags checked by any of these member functions we have just seen we can
use the member function clear( ), which takes no parameters.
Programming Exercises
a) Write a program that reads the characters from the file device.log, then prints them to monitor for
inspection, and then writes them to file daily.log.
The file device.log (must be created before running the program)
Multi-meter

#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
main ( ) {
ofstream ofile;
ifstream ifile;
string name1, name2;
int x;
ifile.open ("device.log");
if (ifile.fail( ))
{ cout << "Input file opening failed.\n";
exit(1); }
ofile.open ("daily.log");
if (ofile.fail( ))
{ cout << "Output file opening failed.\n";
exit(1); }
while (ifile.good())
{ ifile>>name1>>x>>name2;
ofile<<name1<<\t<<x<<\t<<name2<<endl;
cout<< name1<<\t<<x<<\t<<name2<<endl;
ifile.close();
ofile.close();
}

12 units

Oscilloscope 12 units
Breadboard 24 units
Cutters

6 units

b) Create a file which contains the names of electrical devices: such as meter, cutter, breadboard,
pliers, wires etc; and save it as device.log. Write a program that will display the contents of file
device.log on the monitor and also create a file daily.log which stores the same information.
Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 13 of 33

STRUCTURES
Structures
C++ allows a set of variables to be combined together into a single unit called a structure. A
structure is a programmer-defined data type that can hold many different data values.
In other words, structures are collections of related variables under one name. Structures can be used to
store and manipulate dissimilar data items (records).
Before a structured data object can be created or saved, the format of its components must be
defined.
Data for a student :Name : Abu Bakar Mamat
KP_UiTM : 2003123123
Program : EE220
Semester : 4
The component of a structure can be referenced by using the direct component selection operator,
which is a period or dot. The period or dot is preceded by the name of a structure type variable and
is followed by the name of a component.
The way to create a structure is by using the
keyword struct:
struct element { char name[10 ];
char symbol[5];
float aWgt;
float mass;
};
which creates a user-defined data type; struct element.
The variable for this new type is then declared as:
struct element e1;
#include<iostream>
#include<cstring>
using namespace std;
main()
{ struct element { char name[10 ];
char symbol[5];
float aWgt;
float mass;
};
struct element e1;
strcpy (e1.name,"Hydrogen");
strcpy(e1.symbol,"H");
e1.aWgt = 1.0;
e1.mass = 3.0;
// Printing e1 information
cout << "Name : " << e1.name <<endl;
cout << "Symbol : " << e1.symbol <<endl;
cout << "Weight : " << e1.aWgt <<endl;
cout << "Mass : " << e1.mass <<endl; }

#include<iostream>
#include<cstring>
using namespace std;
main()
{ struct student { char name[20];
char kp[11];
char prog[6];
int sem;
};
student aguy;
strcpy( aguy.name,"Abu Bakar Mamat");
strcpy( aguy.kp,"2003123123");
strcpy( aguy.prog,"EE220");
aguy.sem = 4;
// Printing aguy information
cout << "Name : " << aguy.name <<endl;
cout << "KP : " << aguy.kp <<endl;
cout <<"Program : " << aguy.prog <<endl;
cout <<"Semester : " << aguy.sem <<endl;

COMPUTER PROGRAMMING (C++)

The above examples make use of structures to create records, which is the fundamental of database
system. Structures can also be used in basic programming and is used to hold data. The following
example shows how, finding the area of a circle for a given radius:#include <iostream>
using namespace std;
struct Circle { int radius; } ;
main ( )
{ Circle a;
cout << Please enter radius of circle: <<endl;
cin >> a.radius;
cout << The area of the circle with radius <<a.radius<< is
<< 3.1415*a.radius*a.radius<<endl; }

The next example shows how data is stored in a structure and manipulated. This program
multiplies two fractions.
#include <iostream>
using namespace std;
struct FRACTION { int nume;
int deno;
};
main ( )
{ FRACTION fr1, fr2, res;
cout << "Enter first fraction X/Y : \n";
cin >> fr1.nume; cin>> fr1.deno;
cout << "Enter second fraction X/Y : \n";
cin >> fr2.nume; cin>> fr2.deno;
res.nume = fr1.nume * fr2.nume;
res.deno = fr1.deno * fr2.deno;
cout << "Result of "<< fr1.nume<<"/"<< fr1.deno<<" multiplied by "
<< fr2.nume<<"/"<< fr2.deno;
cout << " is "<<res.nume<<"/" << res.deno; }

Assigning values to a structure using initializer list.


#include <iostream>
using namespace std;
struct FRACTION { int nume;
int deno;
}fr1, fr2, res;
main ( )
{ fr1={ 2, 5};
fr2={ 3, 7};
cout << "The first fraction is : "<< fr1.nume<</<<fr1.deno<<endl;
cout << "The second fraction is : "<< fr2.nume<</<<fr2.deno<<endl;
res.nume = fr1.nume * fr2.nume;
res.deno = fr1.deno * fr2.deno;
cout << "Result of "<< fr1.nume<<"/"<< fr1.deno<<" multiplied by "
<< fr2.nume<<"/"<< fr2.deno << " is "<<res.nume<<"/" << res.deno; }

It is up to the programmer to place the structure declaration in the main() function or on top of the
main() function.
CHECK
1. Given the structure:
struct Rectangle { int length;
int width; };

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 15 of 33

Write a program that asks the user to enter the length and width of a rectangle and display the area
and perimeter of the rectangle.
Pointers & Structures
These are fairly straight forward and are easily defined. Consider the following:
struct SAMPLE {
int x;
float t;
char u; };
SAMPLE sam1;
SAMPLE *ptr;
ptr = &sam1;
(*ptr).x = 20; /* to refer to element x in structure */
/* alternatively can be done by: ptr-> x=20; */
Careful: (*ptr).x is NOT the same as *ptr.x or *(ptr.x)
Another example.
struct COORD {
float x,y,z;} pt;
struct COORD *pt_ptr;
pt_ptr = &pt;
/* assigns pointer to pt */
the -> operator lets us access a member of the structure pointed to by a pointer. i.e.:
pt_ptr -> x = 1.0;
pt_ptr->y = pt_ptr -> y - 3.0;
#include <iostream>
using namespace std;
struct Circle { int radius; } ;
main ( )
{ Circle a, *ptr;
ptr=&a;
cout << "Please enter radius of circle: "<<endl;
cin >> (*ptr).radius;
cout << "The area of the circle with radius "<<a.radius<<" is "
<< 3.1415*(*ptr).radius*(*ptr).radius<<endl; }

//Example showing the use of pointer to access structure elements.


#include<iostream>
using namespace std;
main( )
{ struct temp { int num; char ch; };
struct temp var; //declare var of type structure temp
struct temp *ptr; //pointer variable of type structure temp
ptr = &var; //pointer takes the address of the structure variable var
ptr->num=501;
ptr->ch='X';
cout<<"By pointer method";
cout<<"\n\nptr->num = "<<ptr->num;
cout<< "\nptr-> ch = "<<ptr->ch<<endl;;
cout<<"\nBy dot method";
cout<<"\n\nvar.num = "<<var.num;
cout<< "\nvar.ch = "<<var.ch<<endl; }

COMPUTER PROGRAMMING (C++)

Structures and Functions


A structure variable can be passed to a function in similar way as normal argument .
Consider the following examples.
#include <iostream>
using namespace std;
struct person { char name[50];
int age;
float salary; };
void displayData(person); // Function declaration
int main() {
person p;
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
displayData(p); //Function call with structure
//variable as argument
return 0;
}
void displayData(person p1) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
}

#include <iostream>
using namespace std;
struct person {
char name[50];
int age;
float salary;
};
person getData(person);
void displayData(person);
int main() {
person p;
p = getData(p);
displayData(p);
return 0; }
person getData(person p1) {
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
return p1; }
void displayData(person p1) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
}

Enumerated Types
Data type with user-specified values. The syntax is similar to that of structures.
To declare an enumerated type:
enum status {single, married, divorced, widowed };
The tag is status. The user defined data type is enum status. Possible values for any variable of type
enum status are single, married, divorced and widowed. The tag is highly recommended to be
used.
Defining variables of enumerated type.
1. enum status {single, married, divorced, widowed };
enum status status1, status2, status3;
status1 = married;
status2 = single;
2. enum status {single, married, divorced, widowed }statusA, statusB;
statusA = divorced;
statusB = widowed;
Declaring an enumerated type does not allocate storage but only describes the user specified data
and associates integer constants with the values given in braces. By default, the first value is
associated with 0, second with 1, and so on.

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 17 of 33

Example shows the system associates integer constants with the values of an enumerated type.
typedef enum status {single, married, divorced, widowed }MARITAL;
MARITAL status1, status2;
status1 = divorced;
status2 = single;
cout << \n\n, status1);
\*2 is printed*\
cout << \n\n, status2);
\*0 is printed*\
Example shows the system associates integer constants with the values of an enumerated type.
typedef enum status {single=5, married, divorced, widowed }MARITAL;
MARITAL status1, status2,
status1 = divorced;
status2 = single;
cout << \n\n, status1)
\*7 is printed*\
cout << \n\n, status2);
\*5 is printed*\
In the example given only the variable "i" is an
integer. But using the enumeration the named
values are used in a "switch case" statement
with integer value "i".
This is how enum or enumerated data type
used in C++.

#include <iostream>
main()
{ enum Fruits{orange, guava, apple};
Fruits myFruit;
int i;
cout << "Please enter the fruit of your choice(0 to 2)::";
cin >> i;
switch(i)
{ case orange:
cout << "Your fruit is orange";
break;
case guava:
cout << "Your fruit is guava";
break;
case apple:
cout << "Your fruit is apple";
break;
} }

Union Types
Unions offer a way to economize on storage of data. The storage referenced by a union variable can
hold data of different types subject to the restriction that at any one time, the storage holds data of a
single type.
union numbers { char letter; int number; float d_number; };
union numbers num1;
assigning a char value to num1, num1.letter = A; similarly num1.number = 5529; if to assign int to
num1. The assignment of 5529 to num1 cancels the assignment of A to num1 because, at any one
time, num1 holds data of a single type. Similarly, if we write num1.d_number = 99.2;
it will cancel the previous assignment.
In the example given, only "value.num" is assigned, but still the "val.sal" gets a value automatically,
since the memory locations are same.

COMPUTER PROGRAMMING (C++)

#include <iostream>
union Emp
{ int num;
double sal;
};
main()
{ Emp value;
value.num = 2;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
value.sal = 2000.0;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
}

Although structures (including enumerated and union types) are less commonly used today, it is
important that programmers know what they are and how to use them. Understanding of
structures will give a good foundation to understanding classes and objects as they have the same
basic concepts.
The way a structure is declared is similar to the way a class is declared, with the following
differences:
The key word struct is used instead of the key word class.
Although structures can include member functions, they rarely do. So normally a structure
declaration only declares member variables.
Structure declarations normally do not include the access specifiers public or private. Unlike
class members, which are private by default, members of a structure default to being public.

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 19 of 33

OBJECT ORIENTED
PROGRAMMING (OOP)
Traditional procedural-oriented languages (such as C and Pascal) suffer some notable drawbacks in
creating reusable software components:
1. The programs are made up of functions. Functions are often not reusable. It is very difficult
to copy a function from one program and reuse in another program because the function is likely to
reference the headers, global variables and other functions. In other words, functions are not wellencapsulated as a self-contained reusable unit.
2. The procedural languages are not suitable of high-level abstraction for solving real life
problems. For example, C programs uses constructs such as if-else, for-loop, array, function,
pointer, which are low-level and hard to abstract real problems.
In brief, the traditional procedural-languages separate the data structures and algorithms of the
software entities.
Object-oriented programming (OOP) languages are designed to overcome these problems.
1. The basic unit of OOP is a class, which encapsulates both the static attributes and dynamic
behaviors within a "box", and specifies the public interface for using these boxes. Since the class is
well-encapsulated (compared with the function), it is easier to reuse these classes. In other words,
OOP combines the data structures and algorithms of a software entity inside the same box.
2. OOP languages permit higher level of abstraction for solving real-life problems. The
traditional procedural language (such as C and Pascal) forces you to think in terms of the structure
of the computer (e.g. memory bits and bytes, array, decision, loop) rather than thinking in terms of
the problem you are trying to solve. The OOP languages (such as Java, C++, C#) let you think in the
problem space, and use software objects to represent and abstract entities of the problem space to
solve the problem.
Benefits of OOP
The procedural-oriented languages focus on procedures, with function as the basic unit. You need
to first figure out all the functions and then think about how to represent data.
The object-oriented languages focus on components that the user perceives, with objects as the
basic unit. You figure out all the objects by putting all the data and operations that describe the
user's interaction with the data.
Object-Oriented technology has many benefits:
Ease in software design as you could think in the problem space rather than the machine's
bits and bytes. You are dealing with high-level concepts and abstractions. Ease in design leads to
more productive software development.
Ease in software maintenance: object-oriented software are easier to understand, therefore
easier to test, debug, and maintain.
Reusable software: you don't need to keep re-inventing the wheels and re-write the same
functions for different situations. The fastest and safest way of developing a new application is to
reuse existing codes - fully tested and proven codes.

COMPUTER PROGRAMMING (C++)

OOP Basics: Classes and Instances


Class: A class is a definition of objects of the same kind. In other words, a class is a blueprint,
template, or prototype that defines and describes the static attributes and dynamic behaviors
common to all objects of the same kind.
Instance: An instance is a realization of a particular item of a class. In other words, an instance is an
instantiation of a class. All the instances of a class have similar properties, as described in the class
definition.
The term "object" usually refers to instance. But it is often used quite loosely, which may refer to a
class or an instance.
A class can be visualized into three sections:
1. Classname (or identifier): identifies the class.
2. Data Members or Variables (or attributes, states, fields): contains the static attributes of the
class.
3. Member Functions (or methods, behaviors, operations): contains the dynamic operations of
the class.
In other words, a class encapsulates the static attributes (data) and dynamic behaviors (operations
that operate on the data) in a box.
Class Members: The data members and member functions are collectively called class members.
Class Definition
In C++, we use the keyword class to define a class. There are two sections in the class declaration:
private and public, which will be explained later. For examples,
class Circle {
// classname
private:
double radius; // Data members (variables)
string color;
public:
double getRadius(); // Member functions
double getArea();
}
class Player { // classname
private:
int number;
// Data members (variables)
string name;
int x, y;
public:
void run();
// Member functions
void kickBall();
}
Creating Instances of a Class
To create an instance of a class, you have to:
1. Declare an instance identifier (name) of a particular class.
2. Invoke a constructor to construct the instance (i.e., allocate storage for the instance and
initialize the variables).

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 21 of 33

For examples, suppose that we have a class called Circle, we can create instances of Circle as
follows:
// Construct 3 instances of the class Circle: c1, c2, and c3
Circle c1(1.2, "red"); // radius, color
Circle c2(3.4);
// radius, default color
Circle c3;
// default radius and color
Alternatively, you can invoke the constructor explicitly using the following syntax:
Circle c1 = Circle(1.2, "red"); // radius, color
Circle c2 = Circle(3.4);
// radius, default color
Circle c3 = Circle();
// default radius and color
Dot (.) Operator
To reference a member of a object (data member or member function), you must:
1. First identify the instance you are interested in, and then
2. Use the dot operator (.) to reference the member, in the form of
instanceName.memberName.
For example, suppose that we have a class called Circle, with two data members (radius and color)
and two functions (getRadius() andgetArea()). We have created three instances of the class Circle,
namely, c1, c2 and c3. To invoke the function getArea(), you must first identity the instance of
interest, says c2, then use the dot operator, in the form of c2.getArea(), to invoke the getArea()
function of instance c2.
For example,
// Declare and construct instances c1 and c2 of the class Circle
Circle c1(1.2, "blue");
Circle c2(3.4, "green");
// Invoke member function via dot operator
cout << c1.getArea() << endl;
cout << c2.getArea() << endl;
// Reference data members via dot operator
c1.radius = 5.5;
c2.radius = 6.6;
Calling getArea() without identifying the instance is meaningless, as the radius is unknown (there
could be many instances of Circle - each maintaining its own radius).
In general, suppose there is a class called AClass with a data member called aData and a member
function called aFunction(). An instance calledanInstance is constructed for AClass. You use
anInstance.aData and anInstance.aFunction().
Data Members (Variables)
A data member (variable) has a name (or identifier) and a type; and holds a value of that particular
type. A data member can also be an instance of a certain class.
Member Functions
A member function:
1. receives parameters from the caller,
2. perform the operations defined in the function body and
3. returns a piece of result (or void) to the caller.

COMPUTER PROGRAMMING (C++)

Member Function Naming Convention: A function name shall be a verb, or a verb phrase made up
of several words. The first word is in lowercase and the rest of the words are initial-capitalized
(camel-case). For example, getRadius(), getParameterValues().
Putting them Together: An OOP Example
The following program demonstrates the general feature of classes. Member functions setRadius()
and getArea() defined outside the class.
#include <iostream>
using namespace std;
class Circle //specify a class
{
private :
double radius; //class data members
public:
void setRadius(double r);
double getArea(); //member function to return area
};
void Circle :: setRadius(double r)
{
radius = r;
}
double Circle :: getArea()
{
return 3.14 * radius * radius;
}
int main()
{
Circle c1; //define object of class circle
c1.setRadius(2.5); //call member function to initialize radius
cout<<c1.getArea(); //display area of circle object
return 0;
}
Constructors
A constructor is a special function that has the function name same as the classname. In the above
Circle class, we define a constructor as follows:
// Constructor has the same name as the class
Circle(double r = 1.0, string c = "red") {
radius = r;
color = c;
}

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 23 of 33

A constructor is used to construct and initialize all the data members. To create a new instance of a
class, you need to declare the name of the instance and invoke the constructor. For example,
Circle c1(1.2, "blue");
Circle c2(3.4); // default color
Circle c3;
// default radius and color
// Take note that there is no empty bracket ()
A constructor function is different from an ordinary function in the following aspects:
The name of the constructor is the same as the classname.
Constructor has no return type (or implicitly returns void). Hence, no return statement is
allowed inside the constructor's body.
Constructor can only be invoked once to initialize the instance constructed. You cannot call
the constructor afterwards in your program.
Constructors are not inherited (to be explained later).
In the following program constructors, destructor and other member functions are defined inside
class definitions. Since we are using multiple constructor in class so this example also illustrates the
concept of constructor overloading
#include<iostream>
using namespace std;
class Circle //specify a class
{ private :
double radius; //class data members
public:
Circle() //default constructor
{
radius = 0;
}
Circle(double r) //parameterized constructor
{
radius = r;
}
Circle(Circle &t) //copy constructor
{
radius = t.radius;
}
void setRadius(double r) //function to set data
{
radius = r;
}
double getArea()
{
return 3.14 * radius * radius;
}
~Circle() //destructor
{}
};
int main()
{ Circle c1; //defalut constructor invoked
Circle c2(2.5); //parmeterized constructor invoked

COMPUTER PROGRAMMING (C++)

Circle c3(c2); //copy constructor invoked


cout << c1.getArea()<<endl;
cout << c2.getArea()<<endl;
cout << c3.getArea()<<endl;
return 0;
}
Default Constructor
A default constructor is a constructor with no parameters, or having default values for all the
parameters. For example, the above Circle's constructor can be served as default constructor with
all the parameters default.
Circle c1; // Declare c1 as an instance of Circle, and invoke the default constructor
Circle c1(); // Error!
// (This declares c1 as a function that takes no parameter and returns a Circle instance)
If C++, if you did not provide ANY constructor, the compiler automatically provides a default
constructor that does nothing. That is,
ClassName::ClassName() { } // Take no argument and do nothing
Compiler will not provide a default constructor if you define any constructor(s). If all the
constructors you defined require arguments, invoking no-argument default constructor results in
error. This is to allow class designer to make it impossible to create an uninitialized instance, by
NOT providing an explicit default constructor.
Destructor
A destructor, similar to constructor, is a special function that has the same name as the classname,
with a prefix ~, e.g., ~Circle(). Destructor is called implicitly when an object is destroyed.
If you do not define a destructor, the compiler provides a default, which does nothing.
class MyClass {
public:
// The default destructor that does nothing
~MyClass() { }
......
}
"public" vs. "private" Access Control Modifiers
An access control modifier can be used to control the visibility of a data member or a member
function within a class. We begin with the following two access control modifiers:
1. public: The member (data or function) is accessible and available to all in the system.
2. private: The member (data or function) is accessible and available within this class only.
Information Hiding and Encapsulation
A class encapsulates the static attributes and the dynamic behaviors into a "3-compartment box".
Once a class is defined, you can seal up the "box" and put the "box" on the shelve for others to use
and reuse. Anyone can pick up the "box" and use it in their application. This cannot be done in the
traditional procedural-oriented language like C, as the static attributes (or variables) are scattered
over the entire program and header files. You cannot "cut" out a portion of C program, plug into
another program and expect the program to run without extensive changes.

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 25 of 33

Data member of a class are typically hidden from the outside world, with private access control
modifier. Access to the private data members are provided via public assessor functions, e.g.,
getRadius() and getColor().
This follows the principle of information hiding. That is, objects communicate with each others
using well-defined interfaces (public functions). Objects are not allowed to know the
implementation details of others. The implementation details are hidden or encapsulated within the
class. Information hiding facilitates reuse of the class.
Rule of Thumb: Do not make any data member public, unless you have a good reason.
Getters and Setters
To allow other to read the value of a private data member says xxx, you shall provide a get function
(or getter or accessor function) called getXxx(). A getter need not expose the data in raw format. It
can process the data and limit the view of the data others will see. Getters shall not modify the data
member.
To allow other classes to modify the value of a private data member says xxx, you shall provide a
set function (or setter or mutator function) calledsetXxx(). A setter could provide data validation
(such as range checking), and transform the raw data into the internal representation.
Inheritance
The mechanism that allows us to extend the definition of a class without making any physical
changes to the existing class is inheritance.
Inheritance lets you create new classes from existing class. Any new class that you create from an
existing class is called derived class; existing class is called base class.
The inheritance relationship enables a derived class to inherit features from its base class.
Furthermore, the derived class can add new features of its own. Therefore, rather than create
completely new classes from scratch, you can take advantage of inheritance and reduce software
complexity.
Forms of Inheritance
Single Inheritance: It is the inheritance
hierarchy wherein one derived class inherits
from one base class.
Multiple Inheritance: It is the inheritance
hierarchy wherein one derived class inherits
from multiple base class(es)
Hierarchical Inheritance: It is the inheritance
hierarchy wherein multiple subclasses inherit
from one base class.
Multilevel Inheritance: It is the inheritance
hierarchy wherein subclass acts as a base
class for other classes.
Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four
types of inheritance.
In order to derive a class from another, we use a colon (:) in the declaration of the derived class
using the following format :

COMPUTER PROGRAMMING (C++)

class derived_class: memberAccessSpecifier base_class


{
...
};
Where derived_class is the name of the derived class and base_class is the name of the class on
which it is based. The member Access Specifier may be public, protected or private. This access
specifier describes the access level for the members that are inherited from the base class.
Member Access
Specifier
Private
Protected
Public

How Members of the Base Class Appear in the Derived Class


Private members of the base class are inaccessible to the derived class.
Protected members of the base class become private members of the derived class.
Public members of the base class become private members of the derived class.
Private members of the base class are inaccessible to the derived class.
Protected members of the base class become protected members of the derived class.
Public members of the base class become protected members of the derived class.
Private members of the base class are inaccessible to the derived class.
Protected members of the base class become protected members of the derived class.
Public members of the base class become public members of the derived class.

In principle, a derived class inherits every member of a base class except constructor and
destructor. It means private members are also become members of derived class. But they are
inaccessible by the members of derived class.
Following example further explains concept of inheritance:
class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};
class Rectangle: public Shape
{public:
float area ()
{
return (width * height);
};
class Triangle: public Shape
{public:
float area ()
{
return (width * height / 2);
};

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 27 of 33

int main ()
{
Rectangle rect;
Triangle tri;
rect.set_data (5,3);
tri.set_data (2,5);
cout << rect.area() << endl;
cout << tri.area() << endl;
return 0; }
output :
15
5
The object of the class Rectangle contains:
width, height inherited from Shape becomes the protected member of Rectangle.
set_data() inherited from Shape becomes the public member of Rectangle
area is Rectangles own public member
The object of the class Triangle contains:
width, height inherited from Shape becomes the protected member of Triangle.
set_data() inherited from Shape becomes the public member of Triangle
area is Triangles own public member
set_data () and area() are public members of derived class and can be accessed from outside class
i.e. from main()
Constructor and inheritance
The compiler automatically call a base class constructor before executing the derived class
constructor. The compilers default action is to call the default constructor in the base class. If you
want to specify which of several base class constructors should be called during the creation of a
derived class object.
In these cases, you must explicitly specify which base class constructor should be called by the
compiler. This is done by specifying the arguments to the selected base class constructor in the
definition of the derived class constructor.
class Rectangle
{private :
float length;
float width;
public:
Rectangle ()
{
length = 0;
width = 0;

Rectangle (float len, float wid)


{
length = len;
width = wid; }

COMPUTER PROGRAMMING (C++)

float area()
{
return length * width ;

};
class Box : public Rectangle
{private :
float height;
public:
Box ()
{
height = 0;
}
Box (float len, float wid, float ht) : Rectangle(len, wid)
{
height = ht;
}
float volume()
{
return area() * height;

};
int main ()
{
Box bx;
Box cx(4,8,5);
cout << bx.volume() << endl;
cout << cx.volume() << endl;
return 0; }
output :
0
160
Virtual Base Class
Multipath inheritance may lead to duplication of inherited members from a grandparent base class.
This may be avoided by making the common base class a virtual base class. When a class is made a
virtual base class, C++ takes necessary care to see that only one copy of that class is inherited.
class A
{
.....
.....
};
class B1 : virtual public A
{
.....
.....
};

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 29 of 33

class B2 : virtual public A


{
.....
.....
};
class C : public B1, public B2
{
.....// only one copy of A
.....// will be inherited
};
Polymorphism, Virtual Functions and Abstract Class
In C++, a pointer variable of a base class type can point to an object of its derived class. There are
situations when this feature of C++ can be used to develop generic code for a variety of
applications.
Pointer of base class
Consider the following program to understand pointer compatibility property
#include <iostream>
using namespace std;
class Shape
{ protected:
double width, height;
public:
void set_data (double a, double b)
{ width = a;
height = b; }
};
class Rectangle: public Shape
{ public:
double area ()
{
return (width * height); }
};
int main ()
{ Shape *sPtr; //declare pointer variables of type Shape
Rectangle Rect; //create the object rect of type Rectangle
sPtr = &Rect; //make sPtr point to the object rect.
sPtr->set_data (5,3); //set length and width of object rect
cout << sPtr -> area() << endl; //Compile Error !!
return 0;

COMPUTER PROGRAMMING (C++)

Notice that even though rectPtr is pointing to rect (object of type Rectangle), when the program
executes, the statement sets length and width of rectangle. If you tried to access area function of
class Rectangle with sPtr it will give you compiler error.
sPtr -> area() is a compiler error !
It means base class pointer cannot access the additional member function of its derived class. If we
want to do this we need to type cast the base class pointer.
Using Type Casts with Base Class Pointers
We can use a type cast to get the compiler to accept the statement:
static_cast <Rectangle *> (sPtr)->area()
so we should write the statement
cout << static_cast <Rectangle *> (sPtr) -> area() << endl;
The type cast informs the compiler that sPtr is actually pointing to a Rectangle object derived from
the Shape base class. In general, a pointer to a base class that actually points to a derived class
object must first be appropriately cast before the additional features of the derived class can be
used.
Virtual Function and Polymorphism
Virtual functions are used in C++ to support polymorphic behavior. We are modifying the above
program and will introduce you the concept of virtual function by following example:
#include <iostream>
using namespace std;
class Shape
{ protected:
double width, height;
public:
void set_data (double a, double b)
{ width = a;
height = b; }
virtual double area()
{return 0;
}
};
class Rectangle: public Shape
{ public:
double area ()
{
return (width * height);
};

int main ()
{ Shape *sPtr;
Rectangle Rect;

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 31 of 33

sPtr = &Rect;
sPtr -> set_data (5,3);
cout << sPtr -> area() << endl;
return 0; }
Output :
15
A member of a class that can be redefined in its derived classes is known as a virtual member. In
order to declare a member of a class as virtual, we must precede its declaration with the keyword
virtual. The member function area() has been declared as virtual in the base class because it is later
redefined in each derived class. The advantage of having virtual function is that we are able to
access area function of derived class by pointer variable of base class.
Pure Virtual Function and Abstract Class
In above example, base class Shape member function area do not need any implementation because
it is overriding in derived class. If this is the case, the C++ language permits the programmer to
declare the function a pure virtual function. The C++ way of declaring a pure virtual function is to
put the expression = 0 in the class declaration. For example, if a member function double area() is
being declared pure virtual, then its declaration in its class looks like
virtual double area() = 0;
A pure virtual function is sometimes called an abstract function, and a class with at least one pure
virtual function is called an abstract class. The C++ compiler will not allow you to instantiate an
abstract class. Abstract classes can only be subclassed: that is, you can only use them as base classes
from which to derive other classes.
A class derived from an abstract class inherits all functions in the base class, and will itself be an
abstract class unless it overrides all the abstract functions it inherits. The usefulness of abstract
classes lies in the fact that they define an interface that will then have to be supported by objects of
all classes derived from it.
#include <iostream>
using namespace std;
class Shape
{ protected:
double width, height;
public:
void set_data (double a, double b)
{ width = a;
height = b; }
virtual double area() = 0;
};
class Rectangle: public Shape
{public:
double area ()
{
return (width * height); }

};

COMPUTER PROGRAMMING (C++)

class Triangle: public Shape


{public:
double area ()
{
return (width * height)/2;
};

int main ()
{ Shape *sPtr;
Rectangle Rect;
sPtr = &Rect;
sPtr -> set_data (5,3);
cout << "Area of Rectangle is " << sPtr -> area() << endl;
Triangle Tri;
sPtr = &Tri;
sPtr -> set_data (4,6);
cout << "Area of Triangle is " << sPtr -> area() << endl;
return 0;
}
Output :
Area of Rectangle is 15
Area of Triangle is 12

END OF PART II

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015

Page 33 of 33

Вам также может понравиться