University of Nizwa College of Art and Science Computer Science Section

Size: px
Start display at page:

Download "University of Nizwa College of Art and Science Computer Science Section"

Transcription

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

2 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! + x 2 /(2y)! + + x 10 /(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

3 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: Factorial The 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: 1 N! n *( N 1)! if n 0 if n 0 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

4 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: Power x y iteratively defined as: x y = x*x*x* *x (y times) The iterative C++ function to compute x y is: long power (int x,y) int i; long p=1; for (i=1; i<=y; i++) p*=x; return p; 3

5 OOP: Lesson2 Dr. Alaa Aljanaby The recursive definition of x y is: x y 1 x * x y1 if x 0 if x =3* * * * Recursive calls values returned from recursive calls Ex: Write recursive function computes x y. 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 Item The recursive definition is: 0 fib( n) 1 fib( n 1) fib( n 2) if n 0 if n 1 if n 1 4

6 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 Divisor Recursive 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

7 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

8 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

9 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

10 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

11 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; yptr=&y; 5 Memory: yptr y FF 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

12 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; int *aptr; a = 7; aptr = &a; // a is an integer // aptr is a pointer to an integer // 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

13 COMP222: OOP (C++): Lesson3 Dr. Alaa Aljanaby // Cube a variable using the 3 call ways #include <iostream.h> int cube1( int ); void cube2( int * ); void cube3( int & ) // by value // by reference using pointer arguments // 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

14 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 null character ( \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 endof-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

15 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

16 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 Structures Members 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

17 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

18 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 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 OOP Features 1) 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

19 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 Provide public the following member functions SetDate, PrintDate, IncrementDate. Write a driver program to test your class. 26

20 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

21 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

22 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

23 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 Members Member 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

24 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 functions to 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 sales void 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 sales void SalesPerson::printYearSales() cout<< the total sales are= <<totalyearsales()<<endl; 31

25 Programming 2 (C++): Lesson5 Dr. Alaa Aljanaby Initializing Class Objects: Constructors Constructor: 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

26 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 exit function called) o Destructors not called if program terminates with abort Local 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

27 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); int main() Date d2(2,2,2); //Global object //local object of main return 0; Output: Constructor Constructor Destructor Destructor

28 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 //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; ; 35

29 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

30 COMP222: OOP Dr. Alaa Aljanaby Composition: Objects as Member of Classes Composition 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

31 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

32 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

33 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

34 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

35 COMP222: OOP Dr. Alaa Aljanaby Operator Overloading Introduction Operator 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[]

36 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..* ::?: sizeof No new operators can be created 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 Functions Member 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 nonmember function Operator functions as non-member functions Must be friends if needs to access private or protected members

37 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 & )... ;

38 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;

39 COMP222: OOP Dr. Alaa Aljanaby Overloading Binary Operators Overloaded 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;

40 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;

41 COMP222:OOP Dr. Alaa Aljanaby Lesson 8 Inheritance Introduction New 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

42 COMP222:OOP Alaa E Aljanaby Inheritance examples Base class Student Shape Loan Employee Account Derived classes GraduateStudent UndergraduateStudent Circle Triangle Rectangle CarLoan HomeImprovementLoan MortgageLoan FacultyMember StaffMember 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

43 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 ); void setpoint( int, int ); int getx() return x; int gety() return y; // default constructor // set coordinates // get x coordinate // get y coordinate protected: int x, y; ; // accessible by derived classes // 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;

44 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; ; double getradius() return radius; ; void printcentre(); double area(); protected: double radius; ; // set radius // return radius // print centre // calculate area // 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 * 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;

45 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 and the other is run time polymorphism. Compile time polymorphism is functions and 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 functions Using 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).

46 Pointers to base class One of the key features of derived classes is that a pointer to a derived class is typecompatible 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; 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.

47 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;

48 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.

18. Polymorphism. Object Oriented Programming: Pointers to base class // pointers to base class #include <iostream> using namespace std;

18. Polymorphism. Object Oriented Programming: Pointers to base class // pointers to base class #include <iostream> using namespace std; - 126 - Object Oriented Programming: 18. Polymorphism Before getting into this section, it is recommended that you have a proper understanding of pointers and class inheritance. If any of the following

More information

Chapter 19 - C++ Inheritance

Chapter 19 - C++ Inheritance Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions

More information

Chapter 19 C++ Inheritance

Chapter 19 C++ Inheritance Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes

More information

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 CHAPTER 7 CLASSES: PART II 1 Illustrations List (Main Page) Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 Using a Time class with const objects and const member

More information

Inheritance (Deitel chapter 9)

Inheritance (Deitel chapter 9) Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance

More information

Chapter 17 - C++ Classes: Part II

Chapter 17 - C++ Classes: Part II Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend Functions and friend Classes 17.5

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend

More information

Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig Fig. 9.11

Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig Fig. 9.11 CHAPTER 9 INHERITANCE 1 Illustrations List (Main Page) Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig. 9.10 Fig. 9.11 Some simple inheritance examples. An inheritance

More information

Object Oriented Programming. A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.

Object Oriented Programming. A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. Classes (I) Object Oriented Programming A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions Preview Constant Objects and Constant Functions Composition: Objects as Members of a Class Friend functions The use of Friend Functions Some objects need to be modifiable and some do not. A programmer

More information

Data Structures (INE2011)

Data Structures (INE2011) Data Structures (INE2011) Electronics and Communication Engineering Hanyang University Haewoon Nam ( hnam@hanyang.ac.kr ) Lecture 1 1 Data Structures Data? Songs in a smartphone Photos in a camera Files

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

C++ Programming Chapter 7 Pointers

C++ Programming Chapter 7 Pointers C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. All Rights Reserved. 1 Inheritance is a form of software reuse in which you create a class that absorbs an existing class s data and behaviors

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Operator Overloading, Inheritance Lecture 6 February 10, 2005 Fundamentals of Operator Overloading 2 Use operators with objects

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 5: Classes September 14, 2004 Structure Definitions 2 Structures Aggregate data types built using elements of other types

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friends and Overloaded Operators Friend Function Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 3 Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Inheritance S Software reuse inherit a class s data and behaviors and enhance with new capabilities.

More information

PROGRAMMING IN C AND C++:

PROGRAMMING IN C AND C++: PROGRAMMING IN C AND C++: Week 1 1. Introductions 2. Using Dos commands, make a directory: C:\users\YearOfJoining\Sectionx\USERNAME\CS101 3. Getting started with Visual C++. 4. Write a program to print

More information

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan. C++ Classes: Part II Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 17.2 const (Constant) Objects and

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers and Strings Prentice Hall, Inc. All rights reserved. Pointers and Strings 1 Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using const with Pointers Selection Sort Using Pass-by-Reference 2

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

Programming in C# Inheritance and Polymorphism

Programming in C# Inheritance and Polymorphism Programming in C# Inheritance and Polymorphism C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data

More information

Chapter 9 - Object-Oriented Programming: Inheritance

Chapter 9 - Object-Oriented Programming: Inheritance Chapter 9 - Object-Oriented Programming: Inheritance 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship between Superclasses and Subclasses 9.5 Case Study: Three-Level

More information

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C Practical -1 Babaria Institute of Technology LEARN CONCEPTS OF OOP 1. Explain Object Oriented Paradigm with figure. 2. Explain basic Concepts of OOP with example a. Class b. Object c. Data Encapsulation

More information

OOP THROUGH C++(R16) int *x; float *f; char *c;

OOP THROUGH C++(R16) int *x; float *f; char *c; What is pointer and how to declare it? Write the features of pointers? A pointer is a memory variable that stores the address of another variable. Pointer can have any name that is legal for other variables,

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy CISC181 Introduction to Computer Science Dr. McCoy Lecture 27 December 8, 2009 Object Oriented Programming Classes categorize entities that occur in applications. Class teacher captures commonalities of

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

COEN244: Polymorphism

COEN244: Polymorphism COEN244: Polymorphism Aishy Amer Electrical & Computer Engineering Polymorphism means variable behavior / ability to appear in many forms Outline Casting between objects Using pointers to access objects

More information

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples. Outline Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples. 1 Introduction A pointer is a variable that contains a memory address Pointers

More information

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Program Components in C++ 2 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions and Arrays Jan 13, 200 Modules: functionsand classes Programs use new and prepackaged

More information

clarity. In the first form, the access specifier public : is needed to {

clarity. In the first form, the access specifier public : is needed to { Structure Time CSC 211 Intermediate Programming Classes in C++ // Create a structure, set its members, and print it. struct Time // structure definition int hour; // 0-23 int minute; // 0-59 int second;

More information

57:017, Computers in Engineering C++ Classes

57:017, Computers in Engineering C++ Classes 57:017, Computers in Engineering C++ Classes Copyright 1992 2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Introduction Object-oriented programming (OOP) Encapsulates

More information

More C++ : Vectors, Classes, Inheritance, Templates

More C++ : Vectors, Classes, Inheritance, Templates Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit

More information

Classes: A Deeper Look. Systems Programming

Classes: A Deeper Look. Systems Programming Classes: A Deeper Look Systems Programming Deeper into C++ Classes const objects and const member functions Composition Friendship this pointer Dynamic memory management new and delete operators static

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5.4 Calling Functions by Reference 5.5 Using const with Pointers 5.6 Bubble

More information

CS105 C++ Lecture 7. More on Classes, Inheritance

CS105 C++ Lecture 7. More on Classes, Inheritance CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 2 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5. Calling Functions by Reference 5.5 Using const with

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

C Pointers. 7.2 Pointer Variable Definitions and Initialization

C Pointers. 7.2 Pointer Variable Definitions and Initialization 1 7 C Pointers 7.2 Pointer Variable Definitions and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain

More information

Classes: A Deeper Look

Classes: A Deeper Look Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members

More information

Pointers and Strings. Adhi Harmoko S, M.Komp

Pointers and Strings. Adhi Harmoko S, M.Komp Pointers and Strings Adhi Harmoko S, M.Komp Introduction Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable Declarations and

More information

CS250 Final Review Questions

CS250 Final Review Questions CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure that you review all previous exams and make sure you fully understand

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name

More information

CS 115 Exam 3, Spring 2010

CS 115 Exam 3, Spring 2010 Your name: Rules You must briefly explain your answers to receive partial credit. When a snippet of code is given to you, you can assume o that the code is enclosed within some function, even if no function

More information

SFU CMPT Topic: Classes

SFU CMPT Topic: Classes SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables

More information

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

C++ Programming Classes. Michael Griffiths Corporate Information and Computing Services The University of Sheffield

C++ Programming Classes. Michael Griffiths Corporate Information and Computing Services The University of Sheffield C++ Programming Classes Michael Griffiths Corporate Information and Computing Services The University of Sheffield Email m.griffiths@sheffield.ac.uk Presentation Outline Differences between C and C++ Object

More information

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming. Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

Lecture #1. Introduction to Classes and Objects

Lecture #1. Introduction to Classes and Objects Lecture #1 Introduction to Classes and Objects Topics 1. Abstract Data Types 2. Object-Oriented Programming 3. Introduction to Classes 4. Introduction to Objects 5. Defining Member Functions 6. Constructors

More information

More C++ Classes. Systems Programming

More C++ Classes. Systems Programming More C++ Classes Systems Programming C++ Classes Preprocessor Wrapper Time Class Case Study Class Scope and Assessing Class Members Using handles to access class members Access and Utility Functions Destructors

More information

C++ Classes, Constructor & Object Oriented Programming

C++ Classes, Constructor & Object Oriented Programming C++ Classes, Constructor & Object Oriented Programming Object Oriented Programming Programmer thinks about and defines the attributes and behavior of objects. Often the objects are modeled after real-world

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370 Part VII Object-Oriented Programming Philip Blakely (LSC) C++ Introduction 194 / 370 OOP Outline 24 Object-Oriented Programming 25 Member functions 26 Constructors 27 Destructors 28 More constructors Philip

More information

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member

More information

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 1 W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 2 7.4 friend Functions and friend Classes friend function and friend classes Can access private

More information

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1 CS250 Intro to CS II Spring 2017 CS250 - Intro to CS II 1 Topics Virtual Functions Pure Virtual Functions Abstract Classes Concrete Classes Binding Time, Static Binding, Dynamic Binding Overriding vs Redefining

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Fundamentals of Programming Session 24

Fundamentals of Programming Session 24 Fundamentals of Programming Session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24, 2004 2 Classes Structure Definitions 3 Structures Aggregate data types built using elements of other

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

Abstract Data Types. Different Views of Data:

Abstract Data Types. Different Views of Data: Abstract Data Types Representing information is fundamental to computer science. The primary purpose of most computer programs is not to perform calculations, but to store and efficiently retrieve information.

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Lecture 5: Inheritance

Lecture 5: Inheritance McGill University Computer Science Department COMP 322 : Introduction to C++ Winter 2009 Lecture 5: Inheritance Sami Zhioua March 11 th, 2009 1 Inheritance Inheritance is a form of software reusability

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory. Pointer C++ Memory Map Once a program is compiled, C++ creates four logically distinct regions of memory: Code Area : Area to hold the compiled program code Data Area : Area to hold global variables Stack

More information

Lab 2 - Introduction to C++

Lab 2 - Introduction to C++ Lab 2 - Introduction to C++ 2.680 Unmanned Marine Vehicle Autonomy, Sensing and Communications February 8th, 2018 Michael Benjamin, mikerb@mit.edu Henrik Schmidt, henrik@mit.edu Department of Mechanical

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information