University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer...

48
University of Nizwa College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 Dr. Alaa Aljanaby

Transcript of University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer...

Page 1: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

University of Nizwa College of Art and Science Computer Science Section

Object Oriented Programming Lecture Notes

Fall 2011

Dr. Alaa Aljanaby

Page 2: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP- Lesson1 Dr. Alaa Aljanaby

Lesson 1 Refreshing your knowledge

E.G.1: Write C++ program reads in 2 integers and uses a function to find their sum.

E.G.2: Write C++ program reads in 2 integers and uses a function to find their sum, multiplication, and subtraction.

E.G.3: Write C++ program that reads 2 integers and uses function to swap their values.

E.G.4: Write C++ program reads in 2 integer arrays, prints them and finds their sum; use a function for reading, another function for printing, and a function for finding the sum array.

E.G.5: Write C++ program to find: S=x/y! + x2/(2y)! + … + x10/(10y)!Use 2 functions, one for factorial and the other for power.

E.G.6: Write C++ program to read 2 matrices of size 4x4 and finds their multiplication. Use a function for reading, another function for printing, and a function for multiplication.

1

Page 3: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

Lesson 2 Advanced Topics in Functions

2.1 Recursion Recursive function is the function that calls itself either directly or indirectly through another function. Recursive function must contain a condition to stop the recursive calls (stop case).

E.G. 1: FactorialThe factorial of a nonnegative N defined iteratively as: N! = N (N-1) (N-2) … 1

For example: 0! = 1 1! = 1 5! = 5*4*3*2*1=120

The iterative C++ function for factorial is:

unsigned long fact (unsigned long n) { int i; unsigned long f=1; for (i=0; i<=n; i++) f*=i; return f; }

A recursive definition of factorial is:

0n if )!1(*0n if 1

!Nn

N

5! =5* 4! 120 4*3! 24 3*2! 6

2*1! 2 1*0! 1 1

Recursive calls values returned from recursive calls

2

Page 4: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

Write C++ program to find the factorial of the numbers 1, 2, …, 10. Use a recursive function for factorial.

// Recursive factorial function #include <iostream.h>

unsigned long factorial( unsigned long );

int main() { for ( int i = 0; i <= 10; i++ ) cout << i << "! = " << factorial( i ) << endl;

return 0; }

// Recursive definition of function factorial unsigned long factorial( unsigned long number ) { if ( number <= 1 ) // base case return 1; else // recursive case return number * factorial( number - 1 ); }

E.G.2: Powerxy iteratively defined as:

xy= x*x*x* …*x (y times)

The iterative C++ function to compute xy is:

long power (int x,y) { int i; long p=1; for (i=1; i<=y; i++) p*=x; return p; }

3

Page 5: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

The recursive definition of xy is:

0 xif *0 xif 1

1yy

xxx

34 =3* 33 81 3*32 27 3*31 9 3*30 3

1

Recursive calls values returned from recursive calls

Ex: Write recursive function computes xy.

unsigned long power(unsigned long x, y) { if (y==0) return 1; else return x*power(x, y-1) }

E.G.3: Fibonacci series

Seq. 0 1 2 3 4 5 6 7 …Item 0 1 1 2 3 5 8 13 …

The recursive definition is:

1n if )2()1( 1n if 1

0n if 0)(

nfibnfibnfib

4

Page 6: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

// Recursive fibonacci function #include <iostream.h>

unsigned long fibonacci( unsigned long );

int main() { unsigned long result, number;

cout << "Enter an integer: "; cin >> number; result = fibonacci( number ); cout << "Fibonacci(" << number << ") = " << result << endl; return 0; }

// Recursive definition of function fibonacci unsigned long fibonacci( unsigned long n ) { if ( n == 0 || n == 1 ) // base case return n; else // recursive case return fibonacci( n - 1 ) + fibonacci( n - 2 ); }

E.G.4: Greatest Common DivisorRecursive Algorithm:

1. GCD of any number and 0 is the number itself. 2. GCD of the first number (bigger) and the second number (smaller) is

the same as GCD of the second number and the remainder of the division of the first number on the second number.

Ex: Write a recursive function to find GCD of two integers.

5

Page 7: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

2.2 Default Arguments Default arguments are the arguments that have default values provided by the programmer, and when a default argument is omitted in a function call, the default value of that argument is automatically inserted by the compiler and passed in the call. Default arguments must be the rightmost arguments in a function’s parameter list. When one is calling a function with 2 or more default arguments, if an omitted argument is not the rightmost argument in the argument list, all arguments to the right must be omitted. Default arguments should be specified in the first occurrence of the function name – typically, in the prototype.Default arguments can be constants, global variables or function calls.

E.G.: Write C++ program computes the volume of a box. Use a function with default arguments for length, width, and height.

// Using default arguments #include <iostream.h>

int boxVolume( int length = 1, int width = 1, int height = 1 );

int main() { cout << "The default box volume is: " << boxVolume() << "\n\nThe volume of a box with length 10,\n" << "width 1 and height 1 is: " << boxVolume( 10 ) << "\n\nThe volume of a box with length 10,\n" << "width 5 and height 1 is: " << boxVolume( 10, 5 ) << "\n\nThe volume of a box with length 10,\n" << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 ) << endl;

return 0; }

// Calculate the volume of a box int boxVolume( int length, int width, int height ) { return length * width * height; }

6

Page 8: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

2.3 Function Overloading Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least differ in their types). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of arguments in the call.

E.G.: Write C++ program to find the square of a number, integer or double. Use overloaded function.

// Using overloaded functions #include <iostream.h>

int square( int x ) { return x * x; }

double square( double y ) { return y * y; }

int main() { cout << "The square of integer 7 is " << square( 7 ) << "\nThe square of double 7.5 is " << square( 7.5 ) << endl;

return 0; }

7

Page 9: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

2.5 Function Templates Overloaded functions are normally used to perform similar operations that involve different program logic on different data types. If the program logic and operation are identical for each data type, this may be performed by using function templates.The programmer writes a single function template definition. Given the arguments type provided in calls to this function, C++ automatically generates separate template function to handle each type of call appropriately. Thus, defining a single function template defines family of solutions.

E.G.: Write C++ program to find the max value among three values, integers, doubles or characters. Use a template function.

8

Page 10: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

OOP: Lesson2 Dr. Alaa Aljanaby

// Using a function template #include <iostream.h>

template < class T > T maximum( T value1, T value2, T value3 ) { T max = value1;

if ( value2 > max ) max = value2;

if ( value3 > max ) max = value3;

return max; }

int main() { int int1, int2, int3;

cout << "Input three integer values: "; cin >> int1 >> int2 >> int3; cout << "The maximum integer value is: " << maximum( int1, int2, int3 ); // int version

double double1, double2, double3;

cout << "\nInput three double values: "; cin >> double1 >> double2 >> double3; cout << "The maximum double value is: " << maximum( double1, double2, double3 ); // double version

char char1, char2, char3;

cout << "\nInput three characters: "; cin >> char1 >> char2 >> char3; cout << "The maximum character value is: " << maximum( char1, char2, char3 ) // char version << endl;

return 0; }

9

Page 11: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP (C++): Lesson3 Dr. Alaa Aljanaby

Lesson 3 Pointers

Pointers are one of the most powerful features of C++. Pointers enable programs to simulate call by reference, and to create and manipulate dynamic data structures (i.e., data structures that can grow and shrink) such as linked lists, queues, stacks and trees. Pointers are variables contain memory address as their values. A variable directly contains a value (direct reference). A pointer contains an address of a variable that contains a value (indirect reference).

3.1 Pointer Declarations and Initializations int count, *countptr; double *xptr, *yptr; xptr=0; //points to nothing yptr=NULL; //points to nothing

3.2 Pointer Operations Address operator (&) is a unary operator that returns the address of its operand.int y, *yptr; yptr y y=5; 5yptr=&y;

Memory: yptr yFF00

5000 FF00

Indirection operator (*) returns the value to which its operand points. cout<< *yptr<<endl; 5 cout<< y<<endl; 5 *yptr=10; //y=10 cin>>*yptr; //cin>>y

10

Page 12: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP (C++): Lesson3 Dr. Alaa Aljanaby

Note:y, *yptr returns the value of y &y, yptr returns the address of y &yptr returns the address of the pointer *&yptr, &*yptr returns the address of y E.G.: What is the output of the following program?

// Using the & and * operators #include <iostream.h>

int main() { int a; // a is an integer int *aPtr; // aPtr is a pointer to an integer

a = 7; aPtr = &a; // aPtr set to address of a

cout << "The address of a is " << &a << "\nThe value of aPtr is " << aPtr;

cout << "\n\nThe value of a is " << a << "\nThe value of *aPtr is " << *aPtr;

cout << "\n\nShowing that * and & are inverses of " << "each other.\n&*aPtr = " << &*aPtr << "\n*&aPtr = " << *&aPtr << endl; return 0; }

3.3 Calling Functions by Reference There are 3 ways to pass arguments to functions:

1) Call by value 2) Call by reference with reference arguments 3) Call by reference with pointer arguments

Example: Write C++ program to find the cube of an integer. Use 3 functions to calculate the cube one is called by value, the other is called by reference with pointer argument and the last is called by reference with reference argument.

11

Page 13: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP (C++): Lesson3 Dr. Alaa Aljanaby

// Cube a variable using the 3 call ways #include <iostream.h>

int cube1( int ); // by value void cube2( int * ); // by reference using pointer arguments void cube3( int & ) // by reference using reference arguments

int main() { int number = 5; cout << "The original value of number is " << number; number = cube1( number ); cout << "\nThe new value of number is " << number << endl;

number = 5; cout << "The original value of number is " << number; cube2( &number ); cout << "\nThe new value of number is " << number << endl;

number = 5; cout << "The original value of number is " << number; cube3( number ); cout << "\nThe new value of number is " << number << endl; return 0; }

int cube1( int n ) { return n * n * n; // cube local variable n }

void cube2( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; // cube number in main }

void cube3( int &n ) { n = n * n * n; // cube number in main

}

12

Page 14: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson4 Dr. Alaa Aljanaby

Lesson 4 Characters and Strings Processing

A character constant is an integer value represented as a character in single quotes.

‘z’ represents the integer value of z (122 in ASCII code). ‘\n’ represents the integer value of z (10 in ASCII code).

A string is a series of characters treated as a single unit.String literals (string constants) are written in double quotations.

“99 Main Street” (a street address literal) A string in C++ is an array of characters ending with the nullcharacter (‘\0’).A string is accessed via a pointer to the first character (like array).

4.1 Strings Declaration and Reading char color[] = ”blue”; char *colorptr = ”blue”; char color[] = {‘b’, ‘l’, ‘u’, ‘e’, ‘\0’};

char word[20]; cin>>word;

The preceding statement reads characters until a space, tab, new line or end-of-file indicator is encountered. Note that the string is no longer than 19 characters. We can use cin.getline to read a line (more than one word).

char sentence[80]; cin.getline(sentence, 80, ‘\n’);

the above statement reads a line of text from keyboard, the function stops reading when the delimiter ‘\n’ is encountered, when the end-of-file indicator is entered or when the number of characters read so far is one les than the specified length. The cin.getline has ‘\n’ as a default value, so the preceding function call could have been written as:

cin.getline(sentence, 80);

22

Page 15: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson4 Dr. Alaa Aljanaby

4.2 String Manipulation Functions Header file: <string.h>

1. char *strcpy( char *s1, const char *s2); Copies s2 into s1, the value of s1 is returned. 2. char *strcat(char *s1, const char *s2); Append the string s2 to the string s1, the value of s1 is returned. 3. int strcmp(const char *s1, const char *s2); Compares s1 with s2, returns a value of zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively.4. char *strtok(char *s1, const char *s2);

A sequence of calls to strtok breaks string s1 into tokens delimited by characters contained in s2. A pointer to the current token is returned by each call. 5. int strlen(const char *s); Determines the lengthof string s.

E.G1.: if s1>s2 then if (strcmp(s1,s2)>0) s1=s2 strcpy(s1,s2); E.G.2: Tokenizing a statement.

// Using strtok #include <iostream.h> #include <string.h>

int main() { char string[] = "This is a sentence with 7 tokens"; char *tokenPtr;

cout << "The string to be tokenized is:\n" << string << "\n\nThe tokens are:\n";

tokenPtr = strtok( string, " " );

while ( tokenPtr != NULL ) { cout << tokenPtr << '\n'; tokenPtr = strtok( NULL, " " ); }

return 0; }

23

Page 16: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

Lesson 5 Classes and Data Abstraction

5.1 Structure Definition Structures are user defined data types built using elements of other types. struct student { long number; char *name; int mark[3]; float average; };Structures can contain elements of other structs, but it cannot contain an instance of itself. However, a pointer to another struct of the same type can be included. Structures variables are declared like variables of other types: student s, y; student std[10]; student *studentptr;

5.2 Accessing Members of StructuresMembers of a structure (or of a class) are accessed using the member access operator - or dot operator - (.), the arrow operator (->).The dot operator accesses a structure member via the variable name for the object.cin>>s.name; cout<<std[1].average; s.average=(s.mark[0]+s.mark[1]+s.mark[2])/3;

The arrow operator accesses a structure member via a pointer to the object. cin>>studentptr->name;cout<<studentptr->average;cout<<(*studentptr).average //dot operator is higher precedence than * operator

Example: Write C++ program reads in the name, number and average of 100 students using array of structures then print this list sorted alphabetically. The program must contain 3 functions for reading, printing and sorting.

23

Page 17: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

#include <iostream.h> #include <string.h> struct student { char name[20]; long number; float average; };void reading(student *, const int); void sorting(student *, const int); void printing(student *, const int); int main() { const int size=100; student stud[size]; reading(stud, size); sorting(stud, size); printing(stud, size); return 0; }void reading(student *s, const int size) { for (int i=0; i<=size-1; i++) { cout<<"Enter Name,Number and Average\n"; cin>>s[i].name>>s[i].number>>s[i].average; } }void printing(student *s, const int size) { for (int i=0; i<=size-1; i++)

cout<<s[i].name<<"\t"<<s[i].number<<"\t"<<s[i].average<<endl;

}void sorting( student *s, const int size ) { void swap( student * const, student * const ); for ( int i = 0; i <= size - 1; i++ ) for ( int j = 0; j <= size - 2; j++ ) if ( strcmp(s[ j ].name , s[ j + 1 ].name)>0 ) swap( &s[ j ], &s[ j + 1 ] ); }void swap( student * const s1, student * const s2 ) { student hold = *s1; *s1 = *s2; *s2= hold; }

24

Page 18: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

Ex: Write C++ program to reads in name, number and salary of 100 employees using array of structures then perform the following according to user choice: 1: search for employee according to his number. 2: search for employee according to his name. 3: Sort the list in ascending order according to salary. 4: Sort the list alphabetically. 5: Exit program.

5.3 Object Oriented Programming (OOP) The Object-Oriented is the natural way of thinking and of writing computer programs; the unit of OOP is the object. Whereas, the traditional way of programming (procedural programming) is action-oriented and the unit of the program is the function.

5.3.1 OO Design Analyze the problem and determine what objects are needed. Determine what attributes the objects will need to have. Determine what behaviors the objects will need to exhibit. Specify how the objects will needs to interact with each other.

Objects: man, animal, book, car, computer, …etc. Attributes: size, shape, color, weight, …etc. Behaviors: read, walk, sleep, move, …etc.

5.3.2 OOP Features1) Natural way to view the programming process.2) Encapsulation

Data (attributes)+Functions (behaviors)=Abstract Data Type (ADT) 3) Information Hiding. 4) Inheritance relationship.5) Software Reusability.

5.4 Classes Classes enable the programmer to model objects that have attributes(represented as data members) and behaviors (represented as member functions).

25

Page 19: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

E.G.1: Circle class #include <iostream.h> class circle //Circle ADT definition { public: circle(); //default constructor float getarea( ); //returns circle area float getcircumference( ); //returns circle circumference void setradius(float ); //set radius of the circle private: float radius; };circle :: circle( ) { radius=1;} float circle :: getarea( ) { return radius*radius*3.1415;} float circle :: getcircumference( ) { return 2*radius*3.1415;} void circle :: setradius(float r ) { radius=r;}

int main( ) { circle c1,c2; //instantiate 2 objects c1.setradius(5); c2.setradius(10); cout<<c1.getarea( ); cout<<c1.getcircumference( ); cout<<c2.getarea( ); cout<<c2.getcircumference( ); return 0; }

Note: We can define array of objects and a pointer to an object as follows:

Circle c1, //object of type circle Circles[10], //array of circle objects *circleptr; //pointer to a circle object

E.G.2: Create class Date. Use integer variables to represent the private data of this class (day, month, year). Provide a constructor that initializes the the object to 1-1-2000. Provide public the following member functions SetDate,PrintDate, IncrementDate. Write a driver program to test your class.

26

Page 20: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

#include <iostream.h> class Date { public: Date(); void setDate(int, int, int); void printDate(); void incrementDate(); private: int day, month, year; };

Date::Date(){ day=month=1; year=2000; }

void Date::setDate(int d, int m, int y) { day=d; month=m; year=y; }

void Date::printDate() { cout<<"Current date is:"<<day<<"-"<<month<<"-"<<year<<endl;}

void Date::incrementDate() { day++; if (day==31) { day=1; month++; if (month==13) { month=1; year++; } } }int main() { Date d1; d1.printDate(); d1.setDate(29,12,2001); d1.printDate(); d1.incrementDate(); d1.printDate(); d1.incrementDate(); d1.printDate(); return 0; }

27

Page 21: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

E.X.: Create class Rectangle. Provide set and get functions on each private data (width, height). Provide also the following member functions:

GetArea: return the area of the rectangle. GetPerimeter: return the perimeter of the rectangle. IsSquare: return true if the rectangle is square.

5.5 Class Scope and Accessing Class Members Within a class scope, class members are immediately accessible by all of that class member functions and can be referenced by name. The operators used to access class members are identical to those used to access structure members; the dot operator (for objects) and the arrow operator (for pointers).

//Using dot and arrow operators #include <iostream.h> // class circle { same as above }

int main() { circle c1, *circleptr=&c1;

//Using dot opoerator circle.setradius(10); cout<<circle.getarea();

//Using arrow operator circleptr->setradius(10); cout<<circleptr->getarea(); return 0; }

5.7 Separating Interface from Implementation One of the fundamental principles of good software engineering is to separate interface from implementation. Makes it easier to modify programs Header files

Contains class definitions and function prototypes Source-code files

Contains member function definitions

28

Page 22: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

//circle.h: declaration of the circle class (Interface) #ifndef CIRCLE_H #define CIRCLE_H

class circle //Circle ADT definition { public: circle(); //default constructor float getarea( ); //returns circle area float getcircumference( ); //returns circle circumference void setradius(float ); //set radius of the circle private: float radius; };#endif

If time1.h (TIME1_H) is not defined (#ifndef) then it is loaded (#define TIME1_H). If TIME1_H is already defined, then everything up to #endif is ignored. This prevents loading a header file multiple times.

//circle.cpp: Member function definitions//for class circle (Implementation)

#include “circle.h”

circle :: circle( ) { radius=1;} float circle :: getarea( ) { return radius*radius*3.1415;} float circle :: getcircumference( ) { return 2*radius*3.1415;} void circle :: setradius(float r ) { radius=r;}

29

Page 23: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

//Driver for Circle class #include <iostream.h> #include “circle.cpp”

int main( ) { circle c1,c2; //instantiate 2 objects c1.setradius(5); c2.setradius(10); cout<<c1.getarea( ); cout<<c1.getcircumference( ); cout<<c2.getarea( ); cout<<c2.getcircumference( ); return 0; }

5.6 Controlling Access to Class MembersMember Access specifiers:

o Public: Any class member (data or function) is accessible wherever the program has access the object (by any function in the program).

o Private: Any class member (data or function) is accessible only to member functions of this class (and friend classes)(default access mode).

o Protected: Same as private and will b discussed later.

//Accessing private class members #include <iostream.h> #include “circle.cpp” int main() { circle c;

//Error radius is not accessible c.radius=10; cout<<c.radius; return 0; }

30

Page 24: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

5.7 Access Functions and Utility Functions Not all member functions need to be made public to serve as a part of the interface of a class.Some member functions remain private and serve as utility functionsto other functions of the class. Access functions are public functions that read/display data or check conditions.

//Sales Person Class #include <iostream.h> class SalesPerson {public: SalesPerson(); //constructor void setSales(int, double); void printYearSales(); private: double totalYearSales(); //utility function double sales[12]; //12 month sales };

//constructor initialize the array SalesPerson::SalesPerson(){ for (int i=0; i<12; i++) sales[i]=0.0; }

//Function to set monthly salesvoid SalesPerson::setSales(int month, double amount) { if (month>=1 && month<=12 && amount>=0) Sales[month-1]=amount; Else Cout<<”Invalid month or sales amount”<<endl; End if }

//print the total yearly salesvoid SalesPerson::printYearSales() { cout<<”the total sales are=“ <<totalYearSales()<<endl; }

31

Page 25: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

Initializing Class Objects: ConstructorsConstructor:

Is a special member function with the same name as the class Initializes the data members of a class object It is called automatically when an object is created Has no return type.

Note: Data members cannot be initialized where they are declared in the class body. These should be initialized by the class constructor, or they can be assigned values by set functions.

Using Default Arguments with Constructors Date(int=1, int=1, int=2000); //prototype

Date :: Date(int d, int m, int y) //constructor

32

Page 26: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

{ day=d; month=m; year=y; }

Date d1, //all argument defaulted d2(10), //day is 10, month and year defaulted d3(15, 10), //year defaulted d4(15,10,2002); //no default arguments

Using Destructors Destructor:

Is a member function of class Performs termination housekeeping before the system reclaims the object’s memory so that memory may be reused for hold a new object Complement of the constructor Name is tilde (~) followed by the class name (i.e., ~Date)Receives no parameters, returns no value One destructor per class

When Constructors and Destructors Are Called o Constructors and destructors called automatically o Order depends on scope of objects Global scope objects

o Constructors called before any other function (including main)

o Destructors called when main terminates (or exitfunction called)

o Destructors not called if program terminates with abortLocal scope objects

o Constructors called when objects are defined o Destructors called when objects leave scope

i.e., when the block in which they are defined is exited o Destructors not called if the program ends with exit or

abort

33

Page 27: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

#include <iostream.h> class Date { public: Date(int=1, int=1,int=2000); void setDate(int, int, int); void printDate(); void ~Date(); private: int day, month, year; };

Date::Date(int d, int m, int y) { day=d; month=m; year=y; cout<<”Constructor”; printDate(); }

//other function as defined previously

Date::~Date() { cout<<”Destructor”; printDate(); }

Date d1(1,1,1); //Global object

int main() { Date d2(2,2,2); //local object of main

return 0; }

Output:Constructor 1-1-1Constructor 2-2-2

Destructor 2-2-2Destructor 1-1-1

34

Page 28: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

Assignment by Default Memberwise Copy o Assigning objects

o An object can be assigned to another object of the same type using the assignment operator (=)

o Member by member copy // Assignment by default memberwise #include<iostream.h>#include “date.cpp”

int main() { Date date1(7,4,1993 ), date2; // d2 defaults to 1/1/2000 cout << "date1 = "; date1.printDate(); cout << "\ndate2 = "; date2.printDate();

date2 = date1; // assignment by default memberwise copy

cout << "\n\nAfter default memberwise copy, date2 = "; date2.printDate(); cout << endl; return 0; }

Passing Objects to Functions o Objects may be

o Passed as function arguments (call-by-value default) o Returned from functions

35

//passing objects to functions //Class Interface: “Date.h” class Date { public: Date(); void setDay(int); void setMonth(int); void setYear(int); int getDay(); int getMonth(); int getYear(); void printDate(); private: int day, month, year; };

Page 29: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby

#include <iostream.h> #include “date.cpp”

void increaseDate(Date &, const int);

int main() { Date d1(25,12,2002); IncreaseDate(d1, 10); D1.printDate(); Retuen 0; }

void increaseDate(Date &d, const int c) { for(int I=1; I<=c; I++) { d.setDay(d.getDay()+1); if (d.getDay() > 30) { d.setDay(1); d.setMonth(d.getMonth()+1); if (d.getMonth() > 12) { d.setMonth(1); d.setYear(d.getYear()+1); } } } }

36

Page 30: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP Dr. Alaa Aljanaby

Composition: Objects as Member of ClassesComposition

Class has objects of other classes as members

Construction of objects Member objects constructed in order declared Constructed before their enclosing class objects (host objects)

E.G: Create class Employee that contains the private data members firstName, lastName, birthDate and hireDate. Members birthDate and hireDate are const objects of class Date. The program instantiates an Employee object, and initializes and displays its data members.

#include <iostream.h> #include <string.h>

class Date { public: Date( int =1, int =1, int =2000 ); // default constructor void print() const; ~Date(); // provided to confirm destruction order private: int month; //1-12 int day; //1-30 int year; //any year};

37

Page 31: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson6 Alaa E Aljanaby

Date::Date( int d, int m, int y ) { if ( d > 0 && d <= 30 ) // validate the day day = d; else day = 1; if ( m > 0 && m <= 12 ) // validate the month month = m; else month = 1; year = y; // should validate y? cout << "Date object constructor for date "; print(); cout << endl; }

void Date::print() const { cout << day << '/' << month << '/' << year; }

Date::~Date(){ cout << "Date object destructor for date "; print(); cout << endl; }

class Employee { public: Employee( char *, char *, int, int, int, int, int, int); void print() const; ~Employee(); // provided to confirm destruction order private: char firstName[25]; char lastName[25]; Date birthDate; Date hireDate; };

38

Page 32: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP Dr. Alaa Aljanaby

Employee::Employee( char *fname, char *lname, int bday, int bmonth, int byear, int hday, int hmonth, int hyear ) : birthDate(bday, bmonth, byear ), hireDate(hday, hmonth, hyear ) {

strcpy( firstName, fname ); strcpy( lastName, lname );

cout << "Employee object constructor: " << firstName << ' ' << lastName << endl; }

void Employee::print() const { cout << lastName << ", " << firstName << "\nHired: "; hireDate.print(); cout << " Birth date: "; birthDate.print(); cout << endl; }

// Destructor: provided to confirm destruction order Employee::~Employee(){ cout << "Employee object destructor: " << lastName << ", " << firstName << endl; }

int main() { Employee e( "Bob", "Jones", 24, 7, 1968, 3, 12, 1988 );

cout << '\n'; e.print();

return 0; }

39

Page 33: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Programming 2 (C++): Lesson6 Alaa E Aljanaby

The Output:Date object constructor for date 24/7/1968 Date object constructor for date 3/12/1988 Employee object constructor: Bob Jones

Jones, Bob Hired: 3/12/1988 Birth date: 24/7/1968

Employee object destructor: Jones, Bob Date object destructor for date 3/12/1988 Date object destructor for date 24/7/1968

Friend Functions and Friend Classes friend function and friend classes

–Can access private and protected members of another class –friend functions are not member functions of class –Defined outside of class scope

Properties of friendship –Friendship is granted, not taken –Not symmetric (if B a friend of A, A not necessarily a friend of B) –Not transitive (if A a friend of B, B a friend of C, A not necessarily a friend of C)

friend declarations 1. To declare a friend function

– Type friend before the function prototype in the class that is giving friendship – friend int myFunction( int x ); should appear in the class

giving friendship 2. To declare a friend class

– Type friend class Classname in the class that is giving friendship – if ClassOne is granting friendship to ClassTwo, then

friend class ClassTwo; should appear in ClassOne's definition

40

Page 34: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP Dr. Alaa Aljanaby

// Friends can access private members of a class. #include <iostream.h>

class Count { friend void setX( Count &, int ); // friend function friend class Value; //friend class public: Count() { x = 0; } // constructor void print() const { cout << x << endl; } // output private: int x; // data member };

class Value {public: Value() {y=0;} //incrementX can modify x: member of friend calss void incrementX(Count& c) { c.x++; } void incrementY() { y++; } void print() const { cout<<y<<endl; } private: int y; };

// setX is declared as a friend function of Count void setX( Count &c, int val ) { c.x = val; // legal: setX is a friend of Count }

int main() { Count counter; Value v;

cout << "counter.x after instantiation: "; counter.print(); setX( counter, 8 ); // set x with a friend cout << "counter.x after call to setX friend function: "; counter.print(); v.incrementX(counter);//increment x with friend class member v.incrementY(); counter.print(); v.print(); return 0; }

41

Page 35: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP Dr. Alaa Aljanaby

Operator Overloading

IntroductionOperator overloading–Enabling C++’s operators to work with class

objects –Using traditional operators with user-defined objects –Compiler generates the appropriate code based on the manner in which the operator is used

Fundamentals of Operator Overloading Overloading an operator

–Write function definition as normal –Function name is keyword operator followed by the symbol for the operator being overloaded –operator+ used to overload the addition operator (+)

Using operators –To use an operator on a class object it must be overloaded unless the assignment operator(=)or the address operator(&)

Assignment operator by default performs memberwise assignment Address operator (&) by default returns the address of an object

Restrictions on Operator Overloading Operators that can be overloaded

+ - * / % ^ & |

~ ! = < > += -= *=

/= %= ^= &= |= << >> >>=

<<= == != <= >= && || ++

-- ->* , -> [] () new delete

new[] delete[]

Page 36: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP: OOP Alaa E Aljanaby

Overloading restrictions –Precedence of an operator cannot be changed –Associativity of an operator cannot be changed –number of operands cannot be changed

Unary operators remain unary, and binary operators remain binary Operators &, *, + and - each have unary and binary versions Unary and binary versions can be overloaded separately

Operators that cannot be overloaded

No new operators can be created

. .* :: ?: sizeof

–Use only existing operators No overloading operators for built-in types

–Cannot change how two integers are added –Produces a syntax error

Operator Functions as Class Members vs. as friend FunctionsMember vs non-member

–Operator functions can be member or non-member functions Operator functions as member functions

–Leftmost operand must be an object (or reference to an object) of the class

If left operand of a different type, operator function must be a non-member function Operator functions as non-member functions

–Must be friends if needs to access private or protected members

Page 37: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP Dr. Alaa Aljanaby

Overloading Unary Operators Overloading unary operators

–Can be overloaded with no arguments or one argument –Should usually be implemented as member functions

Avoid friend functions and classes because they violate the encapsulation of a class

–Example declaration as a member function: class String { public: bool operator!() const; ... };

–Example declaration as a non-member function class String {

friend bool operator!( const String & ) ... };

Page 38: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP: OOP Alaa E Aljanaby

#include <iostream.h> class rectangle { private: float length, width; public: rectangle(float=1.0, float=1.0); bool operator!() const; };

rectangle::rectangle(float l, float w) { length=l; width=w; }

bool rectangle::operator! () const { if (length==width) return true; else return false; }

int main() { rectangle r1(10,20), r2(20,20); if (!r1) cout<<"r1 is squqre.."; if (!r2) cout<<"r2 is square.."; return 0; }

Page 39: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222: OOP Dr. Alaa Aljanaby

Overloading Binary OperatorsOverloaded Binary operators

–Non-static member function, one argument –Example: class String { public: const String &operator+=( const String & ); ... };

– y += z is equivalent to y.operator+=( z ) –Non-member function, two arguments –Example: class String { friend const String &operator+=( String &, const String & ); ... };

– y += z is equivalent to operator+=( y, z )

#include <iostream.h> class date { friend void operator-=(date&, int); private: int day, month, year; public: date(int=1, int=1, int=2000); void operator +=(int); void print() const; };

date::date(int d, int m, int y) { day=d; month=m; year=y; }

void date::print() const { cout<<day<<"-"<<month<<"-"<<year<<endl; }

Page 40: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP: OOP Alaa E Aljanaby

void date::operator +=(int incr) { for (int i=1; i<=incr; i++) { day++; if (day>30) { day=1; month++; if (month>12) { month=1; year++; } } } }

void operator-=(date &d, int incr) { for (int i=1; i<=incr; i++) { d.day--; if (d.day<1) { d.day=30; d.month--; if (d.month<1) { d.month=12; d.year--; } } } }

int main() { date d1(29,12,2002); d1.print(); d1+=3; d1.print(); d1-=4; d1.print(); return 0; }

Page 41: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222:OOP Dr. Alaa Aljanaby

Lesson 8 Inheritance

IntroductionNew classes created from existing classes

Absorb attributes and behaviors

Derived class –Class that inherits data members and member functions from a previously defined base class

Single inheritance –Class inherits from one base class

Multiple inheritance –Class inherits from multiple base classes

Inheritance: Base Classes and derived classes Base and derived classes

–Often an object from a derived class (subclass) is also an object of a base class (super class)

A rectangle is a derived class in reference to a quadrilateral and a base class in reference to a square

Page 42: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222:OOP Alaa E Aljanaby

Inheritance examples

Base class Derived classes

Student GraduateStudent UndergraduateStudent

Shape Circle TriangleRectangle

Loan CarLoan HomeImprovementLoanMortgageLoan

Employee FacultyMember StaffMember

Account CheckingAccount SavingsAccount

Implementation of public inheritance class CommissionWorker : public Employee {

... }; –Class CommissionWorker inherits from class Employee –friend functions not inherited –private members of base class not accessible from derived class

Protected members Protected access

–Intermediate level of protection between public and private inheritance –Derived-class members can refer to public and protected members of the base class simply by using the member names –Note that protected data “breaks” encapsulation

Page 43: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222:OOP Dr. Alaa Aljanaby

Example: Create class circle inherits data and function members from class point.

#include <iostream.h>

class Point { public: Point( int = 0, int = 0 ); // default constructor void setPoint( int, int ); // set coordinates int getX(){ return x; } // get x coordinate int getY(){ return y; } // get y coordinate

protected: // accessible by derived classes int x, y; // x and y coordinates of the Point };

// Constructor for class Point Point::Point( int a, int b ) { x= a; y=b; }

// Set x and y coordinates of Point void Point::setPoint( int a, int b ) { x = a; y = b; }

Page 44: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

COMP222:OOP Alaa E Aljanaby

class Circle : public Point // Circle inherits from Point {public: // default constructor Circle( double r = 0.0, int a = 0, int b = 0 );

void setRadius( double r) { radius = r; }; // set radius double getRadius() { return radius; }; // return radius void printCentre(); // print centre double area(); // calculate area protected: double radius; };

// Constructor for Circle calls constructor for Point Circle::Circle( double r, int a, int b ) : Point( a, b ){ setRadius( r ); }

double Circle::area() // Calculate area of Circle { return 3.14159 * radius * radius; }

void Circle::printCentre() // print the circle centre { cout<<"Centre=("<<x<<","<<y<<")"<<endl;}

void main() { Point p( 30, 50 ); cout << "X coordinate is: " << p.getX() << endl; cout << "Y coordinate is: " << p.getY() << endl;

Circle c( 2.7, 120, 89 ); cout << "The radius : " << c.getradius()<<endl; c.printCentre(); cout << "X of center: " << c.getX() << endl; cout << "Y of center: " << c.getY() << endl;

c.setPoint(30,70); //change the centre c.printCentre(); cout << "X of center: " << c.getX() << endl; cout << "Y of center: " << c.getY() << endl; }

Page 45: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Polymorphism

In object-oriented programming, polymorphism is a generic term that means 'many shapes'. (from the Greek meaning "having multiple forms").Polymorphism is briefly described as "one interface, many implementations."polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

There are two types of polymorphism one is compile time polymorphism andthe other is run time polymorphism. Compile time polymorphism is functionsand operators overloading. Runtime time polymorphism is done using inheritance and virtual functions. Here are some ways how we implement polymorphism in Object Oriented programming languages

Virtual member functionsUsing virtual member functions in an inheritance hierarchy allows run-time selection of the appropriate member function. A virtual function is a member function of the base class and which is redefined by the derived class. Such functions can have different implementations that are invoked by a run-time determination of the subtype (virtual method invocation, dynamic binding).

Page 46: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Pointers to base class One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature, that brings Object Oriented Methodologies to its full potential.

We are going to start by rewriting our program about the rectangle and the triangle of the previous section taking into consideration this pointer compatibility property:

// pointers to base class#include <iostream.h>

class CPolygon { protected:int width, height;

public:void set_values (int a, int b)

{ width=a; height=b; } };

class CRectangle: public CPolygon { public:int area ()

{ return (width * height); } };

class CTriangle: public CPolygon { public:int area ()

{ return (width * height / 2); } };

int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;

}

2010

In function main, we create two pointers that point to objects of class CPolygon (ppoly1 and ppoly2). Then we assign references torect and trgl to these pointers, and because both are objects of classes derived from CPolygon, both are valid assignment operations.

The only limitation in using *ppoly1 and *ppoly2 instead of rect and trgl is that both *ppoly1 and *ppoly2 are of type CPolygon*and therefore we can only use these pointers to refer to the members that CRectangle and CTriangle inherit from CPolygon.

Page 47: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

For that reason when we call the area() members at the end of the program we have had to use directly the objects rect and trglinstead of the pointers *ppoly1 and *ppoly2.

In order to use area() with the pointers to class CPolygon, this member should also have been declared in the class CPolygon, and not only in its derived classes, but the problem is that CRectangle and CTriangle implement different versions of area, therefore we cannot implement it in the base class. This is when virtual members become useful.

Virtual members 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:

// virtual members#include <iostream.h>

class CPolygon { protected:int width, height;

public:void set_values (int a, int b)

{ width=a; height=b; } virtual int area ()

{ return (0); } };

class CRectangle: public CPolygon { public:int area ()

{ return (width * height); } };

class CTriangle: public CPolygon { public:int area ()

{ return (width * height / 2); } };

int main () { CRectangle rect; CTriangle trgl; CPolygon poly; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; CPolygon * ppoly3 = &poly; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly3->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; cout << ppoly3->area() << endl; return 0;

}

20100

Page 48: University of Nizwa College of Art and Science Computer ... · College of Art and Science Computer Science Section Object Oriented Programming Lecture Notes Fall 2011 ... E.G.3: Fibonacci

Now the three classes (CPolygon, CRectangle and CTriangle) have all the same members: width, height, set_values() and area().

The member function area() has been declared as virtual in the base class because it is later redefined in each derived class. You can verify if you want that if you remove this virtual keyword from the declaration of area() within CPolygon, and then you run the program the result will be 0 for the three polygons instead of 20, 10 and 0. That is because instead of calling the correspondingarea() function for each object (CRectangle::area(), CTriangle::area() and CPolygon::area(),respectively), CPolygon::area()will be called in all cases since the calls are via a pointer whose type is CPolygon*.

Therefore, what the virtual keyword does is to allow a member of a derived class with the same name as one in the base class to be appropriately called from a pointer, and more precisely when the type of the pointer is a pointer to the base class but is pointing to an object of the derived class, as in the above example.

A class that declares or inherits a virtual function is called a polymorphic class.

Note that despite of its virtuality, we have also been able to declare an object of type CPolygon and to call its own area() function, which always returns 0.