OBJECT ORIENTED PROGRAMMING (Practical Manual) DEPARTMENT OF ELECTRONIC ENGINEERING 2nd Semester, 1st Year BATCH -2020 Prepared by: Engr. Talha Tariq CERTIFICATE This is to certify that Mr./Ms. ________________________ with Roll # _______ has successfully completed all the labs prescribed for the course “ Object Oriented Programming”. Lab Instructor External Examiner _______________ Department Of Electronics Engineering Dawood University of Engineering and Technology, Karachi, Pakistan DATED:____________________ Sr.N o 1 2 S.No 1 2 3 3 4 Course Learning Outcomes (CLOs) Of Lab Lab Assessment Plan Assessment Sessiona Final Exam Method l Marks Marks open ended Lab-I 5 x Open ended Lab-II 5 X Complex Engineering activity 10 X Practical Exam / Viva X 15 Practical Exam / Viva x 15 20 30 Total Marks 50 CLO NO CLO_1 CLO_2 CLO_1/CLO _2 CLO_1 CLO_1 Domain & Level PL O Domain & Level PL O Object Oriented Programming INDEX PAGE DAWOOD UNIVERSITY OF ENGINEERING AND Contents S. # 1. Array of Objects Minor improvement Schematic / 3. 4. 5. 6. 7. Sign Classes and Objects Few Errors 2. CLO Mapping Accurate Draw and Improvement Accurate describe required at schematic and Inheritance (Single) schematic some extent. description with errors. have formed (0.5) (0.5) (1) Inheritance (Multiple and Assembly / Hardly able to Operator AssembleOverriding) / Correctly Operation Assemble / operate with assemble and operate no knowledge. operate machine. Minorand Interfaces machine Encapsulation, Abstract Classes improvement (0.5) required. (2) (1) Polymorphism Observation Hardly able to Results with Accurate and results get and errors. observation observe results and results. (0.5) (2) (1) Open Ended Lab- I 8. Operator Overloading 9. Virtual Destructors and Friend Functions 10. Streams and Filing 11. Function Templates and Class Templates 12. Open Ended Lab – II TECHNOLOGY Total (05) Department of Electronic Engineering Subject: Object Oriented Programming Open Ended Lab – I & II LAB # 1 INTRODUCTION TO OBJECTS AND CLASSES Objective To be able to implement the Class in a program. To be able to create objects of a class. Theory Class is just a template or a form of data that define an object. Template means that it doesn’t physically occupy any memory space. But when an object is defined, memory is allocated. The compiler allocates memory space only when an object of the class is defined. A class on its own without any objects does not occupy any space. Class specifies what data and what function will be included in objects of that class. Say for example almost all computer languages have built-in data types like int, is predefined in C++. You can declare as many variables of type int as you need in your program. In a similar way, you can define many objects of the same class. A class contains two types of components: Instance variables: Instance variable serves as data element Methods: Method is a function In C++ terminology the term data member is used to refer to instance variable and the term member functions to refer to methods. A SIMPLE CLASS: Here’s the listing for the sample program that demonstrates the syntax and general features of classes in C++ Program 1: #include <iostream> #include <conio.h> using namespace std; class smallobj // specify a class { private: int somedata; // class data public: void setdata(int d) //member function to set data { somedata = d; } void showdata( ) //member function to display data { cout<< "\nData is " <<somedata; } }; main( ) { smallobj s1,s2; //define two objects of class smallobj s1.setdata(1350); //call member function to set data s2.setdata(2006); s1.showdata(); // call member function to display data s2.showdata(); } SPECIFYING THE CLASS: The specifier starts with the keyword class, followed by the class name smallobj. The body of class is delimited by braces and terminated by a semicolon. The body of class has two parts in it: private and public. As the name suggests, whatever is in private cannot be accessed by any function outside the class. Usually, data is made private while the functions are made public. For the Data hiding feature, data should be made private. CLASS DATA: The small obj class contains one data item: somedata, which is of type int. There can be any number of data items in a class. MEMBER FUNCTIONS: Member functions are functions that are included within a class. There are two member functions in smallobj: setdata( ) and showdata( ). Because setdata( ) and showdata( ) follow the keyword public, they can be accessed from outside the class. USING THE CLASS: DEFINING OBJECTS: The first statement in main( ), smallobj s1, s2; defines two objects, s1 and s2, of class smallobj. Remember that the specification for the class smallobj does not create any objects. It is the definition that actually creates objects that can be used by the program. CALLING MEMBER FUNCTIONS:The following statements calls or access the member function in main( ): s1.setdata(1350); s2.setdtata(2006); To use a member function, the dot operator connects the object name and the member function. The dot operator is also called the class member access operator. Similarly the following two calls to the showdata( ) function will cause the two objects to display their values: s1.showdata( ); s2.showdata( ); CONSTRUCTOR: Sometimes it is convenient if an object can initialize itself when it is first created, without the need to make a separate call to a member function. Automatic initialization is carried out using a special member function called a constructor. A constructor is a memberfunction that is executed automatically whenever object is created. Constructors have exactly the same name as the class of which they are members. This is how a compiler knows they are constructors. Constructors do not use any return type, because they are called automatically by the system and it doesn’t make any sense to return anything. DESTRUCTOR: Like constructor Destructor is a special member function, which is called automatically. Constructor is called when object is created whereas Destructor is called when object is destroyed. A destructor has the same name as the constructor but preceded by a tilde ”~”. Like constructors, destructors do not have return value. They also take no arguments. The most common use of destructor is to deallocate memory that was allocated for the object by the constructor. Program 2: # include <iostream.h> class date { private: int day ; int month ; int year ; public: date () { day = 1; month = 1; year = 2010; } date (int d , int m , int y) { day = d; month = m; year = y; } void show (void) { cout<<day << '/' << month<< "/" << year <<endl; } }; void main (void) { date d1 , d2 ( 11 , 10 , 2010); d1.show(); d2.show() } LAB TASKS L1_P1. Create a date class. Its member data should consist of three integers: day, month, and year. It should also have three member functions: getdate( ) which allows the user to enter a date, showdate( ) which displays the date and changeformat( ) which change the date in mm/dd/yyyy format. L1_P2. Extend the above program with the constructor and destructor L1_P3. Create simple calculator using OOP? LAB OUTCOMES Become familiar with the concept of class and objects. Become familiar with the concept of constructor and destructors. LAB # 2 ARRAY OF OBJECTS OBJECTIVE To understand the concept of arrays and strings and how to use them with objects. THEORY ARRAYS FUNDAMENTALS: Array is a group of similar data items. Arrays are like structures but structures usually group items of different data types whereas an array group items of same data types. The items in structure are accessed by name whereas items in an array are accessed by an index number. The items in an array are called elements. DEFINING ARRAYS: Like other variables an array must be defined before it can be used. An array definition specifies a variable type, name and size of array in [ ]; data typearrayname[size]; int marks[4]; Arrays in C++ are zero-bounded; that is the index of the first element in the array is 0 and the last element is N-1, where N is the size of the array. It is illegal to refer to an element outside of the array bounds, and your program will crash or have unexpected results, depending on the compiler. INITIALIZING ARRAY: When you declare an array, you may use the assignment operator during the variable declaration to initialize the array. You must include the initialization value or values in braces { }’s. int marks[4]={20, 11, 5, 2 } If there is only a single value inside the braces, all elements in the array are initialized to that value. If more than one value is in the braces, separated by commas, the array is initialized beginning with the first element and so on, until the initializing values are assigned. When you run out of values in the initializing list, the remainder of the array is undefined; this is the default value for any array, just like any other variable. ACCESSING ARRAY ELEMENTS: You can access individual array element by array name followed by index number. Like; marks[ j ]; Where j is the array index and j=0, 1 ,…N-1. MULTIDIMENSIONAL ARRAYS: DEFINING MULTIDIMENSIONAL ARRAYS: Multidimensional arrays allow you to represent grids of data of the same type. A two-dimensional array in C++ is built by using two sets of [ ]’s when you define the array. The first dimension of the array is the row, and the second dimension of the array is the column. float Marks[student][test]; INITIALIZING MULTIDIMENSIONAL ARRAY:When initializing multidimensional arrays, you use additional sets of { }’s to contain the row elements, then the columns of rows. float Marks[2][3]={ {6, 9, 7.25} , {6.5, 8, 5} }; ACCESSING MULTIDIMENSIONAL ARRAYS:Array elements in two-dimensional arrays require two indexes. Marks[i][j]; Where i is index for row number and j is for column number. PASSING ARRAYS TO A FUNCTION: Arrays can be used as arguments to function. An sample program given below is shown to demonstrate array as function arguments : ARRAYS OF OBJECTS: Like structures it is also possible to define arrays of objects. The sample program given below demonstrates: an array of such objects. accessing objects in an array. Program 1: #include<iostream> using namespace std; const int MAX=5; class Distance { private: int feet; float inches; public: void getdist() { cout<<" \n Enter feet " ; cin>>feet; cout<<" Enter inches " ; cin>>inches; } void showdist() { cout<<feet<<"'-"<<inches<<"\""; } }; int main( ) { Distance dist[MAX]; //array of objects int n=0; for(int i=0; i<=4; i++) //get distance from user { cout<<" \n Enter distance number "<<i+1; dist[n++].getdist(); //store distance in array } for (int j=0; j<n; j++) { cout<<" \n Distance number "<<j+1<<"is "; dist[j].showdist(); STRINGS: Strings are specialized way to use arrays of type char. As with other data types, strings can be variables or constants. Let’s look an example that demonstrate string variable name and string(array) as class member data. Program 2: #include<iostream> #include<conio.h> using namespace std; #include<string.h> class student { char name[20]; int rollno; float test; public: void setst(char sname[], int rno,float testmrk) { cout<<"name is.........."<<name <<endl; cout<<"sname is.........."<< sname<<endl; strcpy(name,sname); rollno=rno;test=testmrk; cout <<"\nsname argument value is....."<<sname<< endl << "and Now name is..... " << name << endl; } void getst() { cout<<" \nEnter name of student "<<endl; cin>>name; cout<<"\nEnterRollno: "<<endl; cin>>rollno; cout<<"\nEnter test marks "<<endl; cin>>test; cout<<"..................................."; } void show() { cout<<"\nName= "<<name<<"\nRoll no ="<<rollno; cout<<"\nTest marks ="<<test<<"\n"; } }; int main( ) { student s1,s2; s1.getst(); s1.show(); cout<<"\n"; An important aspect of strings in C++ is that they must terminate with a byte containing 0. This terminating 0 is called null character. When the insertion operator displays the string, it displays characters until it encounters the null character. You can initialize a string to a constant value when you define it. Like: char phrase[]=”\n I am a string constant”; READING EMBEDDED BLANKS: Insertion operator consider a space as terminating character. To read text containing blanks we use another function i.e. cin.get( ) which has two arguments, first is the array address and second specifies the maximum size of the array. cin.get(name, max); READING MULTIPLE LINES: In order to read text containing multiple lines the cin.get( ) function will take a third argument . This argument specifies the character that tells the function to stop reading. The default value for this argument is the new line (‘\n’) character. For instance, cin.get(name, max, “#”) Now you can type as many lines as you want. The function will continue to accept characters until you enter the terminating character i.e ‘#’. STRING LIBRARY FUNCTIONS:to use string library function string.h must be #include. strlen(name):- length of string strcpy(destination, source):- copy one string to another. strcat(string1, string2):- concatenate(add) one string to another. ARRAYS OF STRING: If there are arrays of arrays, of course there can be arrays of strings. Like: char record[2][20]={“Ahmed Ali Khan”, “Shahidkhanzada”}; LAB TASKS: L2_P1. Create a class called employee that contains a name (string), an employee number (long) and employee joining date (struct date). Include a member function called getdata( ) to get data from the user for insertion into the object, and another function called displaydata( ) to display the data. Write a main program to exercise this class. It should create 5 objects of class employee and then invite the user to input data. Finally it should print out data for all employees. L2_P2. Create a class Matrix_Math of following type. Class Matrix_Math { Private: int subject_marks[5]; Public: void max_marks(); void min_marks(); void average_marks(); } Lab Outcomes: Student become familiar with the usage of data types with objects. Student become familiar with the application of class and array objects. LAB # 3 INHERITANCE (SINGLE) OBJECTIVE To understand how inheritance promotes software reusability. To understand the notions of base classes and derived classes. THEORY Inheritance is one of the key feature of object-oriented programming including C++ which allows user to create a new class(derived class) from a existing class(base class). The derived class inherits all feature from a base class and it can have additional features of its own. Concept of Inheritance in OOP Suppose, you want to calculate either area, perimeter or diagonal length of a rectangle by taking data(length and width) from user. You can create three different objects( Area, Perimeter and Diagonal) and asks user to enter length and width in each object and calculate corresponding data. But, the better approach would be to create a additional object Rectangle to store value of length and width from user and derive objects Area, Perimeter and Diagonal from Rectangle base class. It is because, all three objects Area, Perimeter and diagonal are related to object Rectangle and you don't need to ask user the input data from these three derived objects as this feature is included in base class. Program : #include <iostream> using namespace std; class Rectangle { protected: float length, width; public: Rectangle() { cout<<"Enter length: "; cin>>length; cout<<"Enter width: "; cin>> width; } }; /* Area class is derived from base class Rectangle. */ class Area : public Rectangle { public: float calc() { return length*width; } }; /* Perimeter class is derived from base class Rectangle. */ class Perimeter : public Rectangle { public: float calc() { return 2*(length+width); } }; int main() { cout<<"Enter data for first rectangle to find area.\n"; Area a; cout<<"Area = "<<a.calc()<<" square meter\n\n"; cout<<"Enter data for second rectangle to find perimeter.\n"; Perimeter p; cout<<"\nPerimeter = "<<p.calc()<<" meter"; return 0; } Inheritance is the process of creating new classes, called derived classes, from existing or base classes. The derived class inherits all the capabilities of the base class but can add embellishments and refinements of its own. The base class is unchanged by this process. Inheritance is an essential part of OOP. Classes create a hierarchy, which is usually shown as a tree, where base classes are higher in the tree. Inheritance can be used for: 1) Add data and code to a class without having to change the original class. 2) Reuse code 3) Change the behavior of class. DERIVED CLASS AND BASE CLASS: Let’s suppose that we have worked long and hard to make a Class operate just the way we want, and we are satisfied with the results. Now after sometime we need to add any feature to that class. We could insert the feature by writing member function directly into the source code of that Class. However there are several reasons why we might not want to do this. First, our class works well and has undergone many hours of testing and debugging. If we start changing the source code of the Class, the testing process will need to be carried out again, and of course we may foul something up and spend hours debugging code that worked fine before we modified it. Second we might not have access to the source code of the existing Class, especially if it had been distributed as part of a class library. Program 2: #include<iostream.h> #include<conio.h> class animal { public: void speak() { cout<< "animal can speak" << endl; } }; class cat : public animal { public: void jump() { cout<< "cat jumping"<<endl; } }; class tiger: public animal { public: void attack() { cout<< "attacking" <<endl; } }; int main() { animal a; a.speak(); cat c1; c1.jump(); c1.speak(); tiger t; t.attack(); ACCESSING BASE CLASS MEMBERS: t.speak(); } It is very important to know when a member function in a base class can be used by object of the derived class. This is called accessibility. Substituting base class member functions: Accessbility private protected public Accessible from own class ? yes yes yes Accessible from derviedclass ? no yes yes Accessible outside derviedclass ? no no yes THE PROTECTED ACCESS SPECIFIER: With inheritance, however, the member functions of the derived classs need to access data member of the base class to achieve reusability. The member funcitons cannot access private members. Also we don’t want to make data members public, since that would allow it to be accessed by any funciton anywhere in the program and eliminate the advantages of data hiding. A protected member can be accessed by member functions in its own class or in any clas derived from its own class. It cannot be accesed from functions outside these classes. If you are writing a class that you suspect might be used, at any point in the future, as a base class for other classes, then any data or functions that the derived classes might need to access should be made protected rather than private. This ensures that the class is “inheritance ready”. Lab Task: 1: Wrire down the basic program using inheritance concept; at least using more than two child class derived from basic class. 2: using inheritance, add two variables, in derived class used multiplication feature…. Lab Outcomes Student become familiar with the concept of Inheritance. Student become familiar with the keywords of base and derived classes. LAB # 4 MULTIPLE INHERITANCE OBJECTIVE To be able to create new classes by inheriting from two or more classes. THEORY Multiple inheritance is a feature of object-oriented computer programming languages in which a class can inherit characteristics and features from more than one super class. It is distinct from single inheritance, where a class may only inherit from one particular super class. A B C In the above figure the class C is deriving from class A and class B. The syntax for multiple Inheritance is similar to that for single Inheritance.In this situation the relationship is expressed like this Class A { }; Class B { }; Class C :public A, public B { }; // base class A // base class B // C is derived from A and B Program 1: #include<iostream.h> #include<conio.h> class student { protected: int rno,m1,m2; public: void get() { cout<<"Enter the Roll no :"; cin>>rno; cout<<"Enter the two marks :"; cin>>m1>>m2; } }; class sports { protected: int sm; // sm = Sports mark public: void getsm() { cout<<"\nEnter the sports mark :"; cin>>sm; } }; class statement:public student,public sports { int tot,avg; public: void display() { tot=(m1+m2+sm); avg=tot/3; cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal cout<<"\n\tAverage : "<<avg; } }; main() { statement obj; obj.get(); obj.getsm(); obj.display(); getch(); } Program2 Multiple Inheritannce: : "<<tot; #include <iostream.h> # include <conio.h> class Date { protected: int day; int month; int year; public: Date() { day = 1 ; month = 10; year = 2000; } Date (int d, int m, int y) { day = d; month = m; year = y; } void showDate () { cout << "Date is: " << day << "/" << month << "/" << year << endl;} }; class Time { protected: int hour; int minute; int second; public: Time() { hour = 12; minute = 30 ; second = 0; } Time (int h, int m, int s) { hour = h; minute = m; second = s; } void showTime () { cout << "Time is: " << hour << ":" << minute << ":" << second << endl; } }; class DateTime : public Date, public Time { public: DateTime () : Date(), Time() { } DateTime (int d, int m, int y, int h, int mm, int s) : Date (d,m,y), Time(h,mm,s) { } void showDateTime () { showDate(); showTime(); } }; int main () { DateTime dt(23,2,2015,9,55,30); dt.showDateTime(); Date d; d.showDate(); Time t; t.showTime(); } Program3: inheritance #include <iostream.h> class Date { protected: int day; int month; int year; public: Date() { day = 1; month = 1; year = 2000; } Date (int d, int m, int y) { day = d; month = m; year = y; } void showDate () { cout << "Date is: " << day << "/" << month << "/" << year << endl; } }; class DateTime : public Date { private: int hour; int minute; int second; public: DateTime() : Date() { hour = 12; minute = 30; second = 0; } DateTime (int d, int m, int y, int h, int mm, int s) { day = d; month = m; year = y; hour = h; minute = mm; second = s; } void showDateTime () { showDate(); cout << "Time is: " << hour << ":" << minute << ":" << second << endl; } }; int main () { DateTime dt(23,2,2015,9,55,30); dt.showDateTime(); } Task: 1:Write down a simple program using multiple inheritance. 2: write down a program using multiple inheritance, using following scenario. Learning Outcomes: Student become familiar with the types of Inheritance Student become familiar with how to utilize inheritance. LAB # 05 ENCAPSULATION, ABSTRACT CLASSES AND INTERFACES OBJECTIVE: To understand concepts of encapsulation, abstract classes and Interfaces. THEORY: Data Encapsulation: All C++ programs are composed of the following two fundamental elements: 1. Program statements (code): This is the part of a program that performs actions and they are called functions. 2. Program data: The data is the information of the program which affected by the program functions. Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Data encapsulation is a mechanism of bundling the data, and the functions that use them. C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example: class Box { public: double getVolume(void) { return length * width * height; } private: double length; // Length of a box double width; // widthof a box double height; // Height of a box }; The variables length, width, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved. To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program. Making one class a friend of another exposes the implementation details and reduces encapsulation. The idea is to keep as many of the details of each class hidden from all other classes as possible. DATA ABSTRACTION: Data abstraction refers to providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Data Encapsulation Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Interfaces: An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. C++ classes provides great level of data abstraction . They provide sufficient public methods to outside the world to play with the functionality of the objects and to manipulate object data i.e .. state without actually knowing how class has been implemented internally. Data Encapsulation Example: Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example: #include <iostream> using namespace std; class Adder{ public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { // total = total+number total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main( ) { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout<< "Total " <<a.getTotal() <<endl; return 0; } Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly. Abstract Class: A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows: class Box { public: // pure virtual function virtual double getVolume() = 0; private: double length; // Length of a box double wdidth; // width of a box double height; // Height of a box }; The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error. Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error. Abstract Class Example: Consider the following example where parent class provides an interface to the base class to implement a function called getArea(): Example2: #include <iostream> using namespace std; // Base class class Shape { public: // pure virtual function providing interface framework. virtual int getArea() = 0; void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived classes class Rectangle: public Shape { public: int getArea() { return (width * height); } }; class Triangle: public Shape { public: int getArea() { return (width * height)/2; } }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(2); Rect.setHeight(7); // Print the area of the object. cout<< "Total Rectangle area: " <<Rect.getArea() <<endl; Tri.setWidth(2); Tri.setHeight(7); // Print the area of the object. cout<< "Total Triangle area: " <<Tri.getArea() <<endl; return 0; } You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape. Designing Strategy: An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that all operate similarly. The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application. This architecture also allows new applications to be added to a system easily, even after the system has been defined. LAB TASKS L5_P1. Write a program to find out the payroll system using encapsulation. Declare the base class emp. Define and declare the function get() to get the employee details (id, name, designation). Declare the derived class salary. Declare and define the function get1() to get the salary details (basic pay, home allowance, health allowance,tax). Define the function calculate() to find the net pay. Define the function display(). NOTE: net pay = basic pay + home allowance + health allowance – tax; L5_P2 Modify the above program using abstract class concept. Learning Outcomes Student become familiar with what is data hiding. Student become familiar with the encapsulation and abstraction. LAB # 6 POLYMORPHISM OBJECTIVE To understand the concept of Polymorphism To be able to use Pure Virtual Functions To understand the concept of Abstract Base class THEORY POLYMORPHISM: Poly means many and morphism means form. Polymorphism therefore is the ability for objects of different classes related by inheritance to response differently to the same function call. Polymorphism is achieved by means of virtual functions. It is rendered possible by the fact that one pointer to a base class object may also point to any object of its derived class. VIRTUAL FUNCTION: A virtual function is a special type of member function. It is defined in the base class and may be redefined in any class derived from this base class. Its name in the base class and in the derived classes remains the same. Its definition in these classes may be different. A virtual function in derived class is executed through the pointer of the public base class. The derived classes may have different versions of small virtual functions. A virtual function may be redefined in the derived classes. A redefined function is said to override the base class function. EARLY BINDING: The events that take place at the compile-time are called early binding. It is also called static binding. It indicates that all information required to call a function is known at the compile-time. The compiler decides at compile-time what method will respond to the message sent to the pointer. The accessing of member functions of a class through the pointer is an example of early binding. The compiler decides at compile-time to always execute the member function of the class whose type matches the type of the pointer irrespective of the contents of the pointer. Thus whatever the object points to during execution of the program, the pointer always accesses the member of the class whose type matches with its type. Program :1 #include <iostream.h> class Cola { public: virtual void color(){cout<<"No Color"<<endl;}//Virtual Function }; class Pepsi : public Cola { public: void color() {cout<< "Black" <<endl; } }; class Fanta : public Cola { public: void color() {cout<< "Orange" <<endl; } }; int main (void) { Cola *a; Fanta f; Pepsi p; a=&f; a->color(); a=&p; a->color(); // Cola c; // a= &c; //a->color(); } In program 1, the key word “virtual” appears only in the definition of the base class Cola; it has not been repeated in the derived classes Pepsi and Fanta that are derived from the base class Cola. Each derived class Pepsi and Fanta and the base class Cola have a member function with the same name, i.e. color. The statement “a=&f;” assigns the address of an object of class Cola to the pointer object “a” when the statement “a->color();” is executed for the first time, the pointer object of the base class contains the address of the object of the derived class Fanta and the virtual member function of the derived class Fanta is executed. Similarly, when the “a->color();” statement is executed for the second time the pointer object ‘a’ of the base class contains the address of the derived class Pepsi and thus the virtual member function of the derived class Pepsi is executed. In executing virtual function, the computer selects the function to be called based on the contents of the pointer and not on the basis of the type of the pointer. PURE VIRTUAL FUNCTION: The virtual function that is only declared but not defined in the base class is called a pure virtual function. A function is made pure virtual by preceding its declaration with the keyword virtual and by post fixing it with =0. The pure virtual function simply tells the compiler that the function is pure. The class that contains the pure virtual function exists only to act as a parent or base of the derived classes. This function is implemented in the derived classes. Program 2: #include <iostream.h> class Country { public: virtual void language()=0; //Pure Virtual Function }; class Africa : public Country { public: void language() {cout<< "Swahili" <<endl; } }; class Azerbaijan : public Country { public: void language() {cout<< "Azeri" <<endl; } }; void main (void) { Country *ptr; ptr=new Azerbaijan(); ptr->language(); ptr=new Africa(); ptr->language(); //Country c; } ABSTRACT BASE CLASS The base class that has one or more pure virtual functions is called the Abstract Base Class. These classes are designed as a framework of layout for derived classes. An abstract base class cannot be instantiated, i.e. an object of its type cannot be defined. But, a pointer to an abstract base class can be defined. The derived class that does not have any pure virtual function is called Concrete Derived Class. The pure virtual function of the Abstract Base Class is implemented in the Concrete Derived Class. The derived classes usually have their own versions of the virtual functions. In Object Oriented Programming a hierarchy of classes is defined. The Abstract Base Class is defined at the top of this hierarchy. The Concrete Derived Classes are derived from the Abstract Base Class. The pure virtual functions are declared in the base class. Each derived class contains its own version of these pure virtual functions. In this way uniformity is achieved within the hierarchy of the class. An abstract base CPolygon class could look like this: // abstract class CPolygon class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtua int area () =0; }; LAB TASKS L6_P1. Implement the polymorphism concept using following structure. Class shape: Functions: virtual void draw () =0; Derive Class Circle from Shape class: Functions: void draw () { cout<<”Circle “<<endl; }; Derive Class Square from Shape class: Functions: void draw () { cout<<”Square “<<endl; }; L6_P2 write the program using polymorphism concept, having basic class Animal, derive two classes lion and tiger, base class have one pure virtual function Attack . L6_ P3: write the program using polymorphism concept, having base class shape, derive two any three classes, calculate their area, parameters. Learning Outcomes Student become familiar with the concept of polymorphism. Student become familiar with the utilization of polymorphism. LAB # 7 OPERATOR OVERLOADING OBJECTIVE To become familiar with the concept of operator overloading To be able to use this technique in programming THEORY OPERATOR OVERLOADING: C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively. Operator overloading allows the programmer to define how operators (such as +, -, ==, =, and !) should interact with various data types. Because operators in C++ are implemented as functions, operator overloading works very analogously to function overloading. Operators are overloaded by writing a function definition as you normally would, except that the function name now becomes the keyword operator followed by the symbol for the operator being overloaded. The following operators cannot be overloaded: C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively. When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. Function overloading in C++: Function overloading is a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters. You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You can not overload function declarations that differ only by return type. Following is the example where same function print() is being used to print different data types: #include <iostream.h> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } }; int main(void) { printData pd; pd.print(5); pd.print(500.263); } OVERLOADING UNARY OPERATOR: Unary operators act on only one operand. Examples of unary operators are ++, -- , and unary minus as in -60. These operators do not work directly with the object. Every time you want to increment any object you need to call a member function defined for that purpose. But the listing would be more readable if we could have used the increment operator ++ instead of calling function. The program given below demonstrates how increment operator is overloaded and used with objects. #include<iostream.h> class counter { public: int count; counter() { count = 0; } int getcount() { return count; } counter operator ++( ) { ++count; // increment count return counter(); // return unnamed temporary object } }; int main( ) { counter c1, c2; cout<< "\n c1= " << c1.getcount( ); cout<< "\n c2= " << c2.getcount( ); ++c1; ++c2; ++c1; cout<< "\nc1= " << c1.getcount( ); cout<< "\nc2= " << c2.getcount( ); } #include<iostream.h> class complex { public: int a,b,c; void getvalue() { cout<<"Enter the Two Numbers:"; cin>>a>>b; } void operator++() { a=++a; b=++b;} void operator--() { a= --a; b= --b; } void display() { cout<<a<<","<<b<<endl; } }; int main() { complex obj; obj.getvalue(); ++obj; cout<<"Increment Number\n"; obj.display(); --obj; cout<<"Decrement Number\n"; obj.display(); } OVERLOADING BINARY OPERATORS: Like unary operators binary operators can also be overloaded. If you want to perform any binary operation like add, subtract, divide, multiply and compare two objects you need to call member functions written to perform these operations. By overloading binary operators we can reduce our programming code and simplify our statement. The example program demonstrates how arithmetic, comparison, and arithmetic assignment operators are overloaded. Program : #include <iostream.h> class binary { public: int x; binary(){ x=0;} binary (int a){ x =a;} void getvalue( ) { cout<< "\n\tEnter value for x: "; cin>> x; } void displayvalue() { cout<<"\nvalue of x is: " << x <<endl; } binary operator +(binary b) { return binary(x+b.x); } }; main() { binary a,b,c; //Objects a, b, c created cout<<"\nEnter value for Object A:"; a.getvalue( ); cout<<"\nEnter value for Object B:"; b.getvalue( ); c= a + b; //Binary Overloaded operator used cout<< "\n\nFor object A:" ; a.displayvalue(); cout<< "\n\nFor object B:" ; b.displayvalue(); cout<< "\n\nFor object C:" ; c.displayvalue(); cout<<endl; } OUTPUT: LAB TASKS L7_P1. Write down the program using function overloading concepts, at least four function should be overloaded. Learning outcome Student become familiar with the concept of overloading. Student become familiar with the types of overloading. LAB # 8 VIRTUAL DESTRUCTORS & FRIEND FUNCTIONS OBJECTIVE To understand the concept of virtual destructors To be able to use Friend Functions THEORY VIRTUAL DESTRUCTORS: As you may know, in C++ a destructor is generally used to deallocate memory and do some other cleanup for a class object and it’s class members whenever an object is destroyed. Destructors are distinguished by the tilde, the ‘~’ that appears in front of the destructor name. In order to define a virtual destructor, all you have to do is simply add the keyword “virtual” before the tilde symbol. The need for virtual destructors in C++ is best illustrated by some examples. Let’s start by going through an example that does not use virtual destructors, and then we will go through an example that does use virtual destructors. Once you see the difference, you will understand why virtual destructors are needed. Take a look at the code below to start out: Program 1 (without a Virtual Destructor): #include <iostream.h> class Base { public: Base(){ cout<<"Constructing Base"<<endl;} // this is a destructor: ~Base(){ cout<<"Destroying Base"<<endl;} }; class Derive: public Base { public: Derive(){ cout<<"Constructing Derive"<<endl;} ~Derive(){ cout<<"Destroying Derive"<<endl;} }; main() { Base *P = new Derive(); /*Base *p; p=new Derive; delete p; delete p;*/ delete P; } The output of this program is: Based on the output above, we can see that the constructors get called in the appropriate order when we create the Derive class object pointer in the main function. But there is a major problem with the code above: the destructor for the "Derive" class does not get called at all when we delete ‘basePtr’. So, how can we fix this problem? Well, what we can do is make the base class destructor virtual, and that will ensure that the destructor for any class that derives from Base (in our case, its the "Derive" class) will be called. Program 2 with a Virtual Destructor: class Base { public: Base(){ cout<<"Constructing Base";} // this is a virtual destructor: virtual ~Base(){ cout<<"Destroying Base";} }; Now, with that change, the output after running the code will be: Note that the derived class destructor will be called before the base class. So, now you’ve seen why we need virtual destructors and also how they work.One important design paradigm of class design is that if a class has one or more virtual functions, then that class should also have a virtual destructor. FRIEND FUNCTIONS: A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. Program 3 (Demonstrate working of friend Function): #include <iostream> using namespace std; class Distance { private: int meter; public: Distance(): meter(0){ } friend int func(Distance); //friend function }; int func(Distance d) //function definition { d.meter=5; //accessing private data from non-member function return d.meter; } int main() { Distance D; cout<<"Distace: "<<func(D)<<endl; return 0; } Output: Here, friend function func() is declared inside Distance class. So, the private data can be accessed from this function. Though this example gives you what idea about the concept of friend function Suppose, you need to operate on objects of two different classes then, friend function can be very helpful. You can operate on two objects of different class without using friend function but, your program will be long, complex and hard to understand. Program 4 (to operate on Objects of three Different class using friend Function): #include <iostream.h> class charlie; class bravo; class alpha { private: int x; public: alpha(): x(3){}; friend int addABC(alpha, bravo, charlie); }; class bravo { private: int y; public: bravo(): y(7){}; friend int addABC(alpha, bravo, charlie); }; class charlie { private: int z; public: charlie(): z(5){}; friend int addABC(alpha, bravo, charlie); }; int addABC(alpha a, bravo b, charlie c) { cout<<"Alpha = "<<a.x<<endl; cout<<"Bravo = "<<b.y<<endl; cout<<"Charlie = "<<c.z<<endl; cout<<"Alpha+Bravo+Charlie = "; return (a.x + b.y + c.z); } main () { alpha aa; bravo bb; charlie cc; cout<<"Adding Alpha Bravo Charlie:"<<endl; cout<<addABC(aa, bb, cc)<<endl;} OUTPUT: In above Program , the three classes are alpha, bravo and charlie, the constructors in these classes initialize their single data items to fixed values. The requirement of addABC() was to have access to their private data members, so it has been made a friend function of all the three classes, by declaring addABC() in all three classes, with the keyword ’friend’. Friend int addABC(alpha, bravo, charlie); This declaration can be placed anywhere in the class; it doesn’t matter if it goes in the public or the private section. An object of each class is passed as an argument to the function addABC(), and it accesses the private data member of all classes through these arguments. The function doesn’t do much: It adds the data items and returns the sum. The main() program calls this function and prints the result. Remember that a class can’t be referred to until it has been declared. Class bravo and class Charlie are referred to in the declaration of the function addABC() in class alpha, so bravo and Charlie must be declared before alpha. Hence the declaration classcharlie; class bravo; at the beginning of the program. LAB TASKS L8_P1. Write a Distance class ,that contains private variables inches, feet, now declares a friend Function named DistSqr(). This friend function should take a distance value as an argument, and return the square of the distance. Write a main program to test this class. (Hint: to square the distance, convert it into feet, and then take square.) L8_P2. Implement the following pseudo code. Class A { Data type: integer no1; Function: friend function by the name SUM (). } Class B { Data type: integer no2; Function: friend function by the name SUM (). } SUM () should add the values no1, no2 from class A and B respectively. Learning Outcomes: Student become familiar with the concept of Virtual Destructor. Student become familiar with the friend function. LAB # 9 STREAMS AND FILING OBJECTIVE To understand the concept of files and streams THEORY STREAMS: A stream is a general name given to a flow of data. In C++ a stream is represented by an object of a particular class. So far cinand coutstream objects have been used. Different streams are used to represent different kinds of data flow. For example, the ifstreamclass represents data flow from input disk files. FILES: A file is just a bunch of bytes stored on a hard disk. Some have a specific structure others don’t. Files are used to save info so that it can be retrieved later for use. By default if a file does not exist, a new one is created, as the program is executed. TYPES OF FILES: There are two types of files; text files and binary files. In text files data is stored as readable characters; whereas binary files are in machine language. If abc123is outputted to a text file, abc123 can be seen in the output file, but in a binary file only a bunch of black blocks will be displayed if notepad is used. The binary files are smaller in size. The default mode is text mode when a file is opened. FSTREAM.H: fstream.hprovides simultaneous input and output through ifstream, ofstreamandfstream. 1. ifstream - open the file for input 2. ofstream - open the file for output 3. fstream - open the file for input/output/both OPEN A FILE The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags: ios::in Open for input operations. ios::out Open for output operations. ios::binary Open in binary mode. All output operations are performed at the end of the file, appending the content to ios::app the current content of the file. This flag can only be used in streams open for output-only operations. If the file opened for output operations already existed before, its previous content ios::trunc is deleted and replaced by the new one. All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the fileexample.bin in binary mode to add data we could do it by the following call to member function open(): 1 ofstreammyfile; 2 myfile.open ("example.bin", ios::out | ios::app | ios::binary); Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument: class default mode parameter ofstream ios::out ifstream ios::in fstream ios::in | ios::out For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function. The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden,notcombined. File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters). Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefore, we could also have declared theprevious myfile object and conducted the same opening operation in our previous example by writing: ofstreammyfile ("example.bin", ios::out | ios::app | ios::binary); Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent. To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise: if (myfile.is_open()) { /* ok, proceed with output */ } CLOSING A FILE When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file: myfile.close() ; Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes. In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close(). STEPS FOR WRITING TO A FILE: 1. Declare an ofstream variable. 2. Open a file with it. 3. Write to the file (there are a couple of ways.) 4. Close it. Program 1: #include <fstream.h> void main(void) { ofstream file; file.open("file.txt"); //open a file file<<"Hi !"<<endl; //write to it file<<"This is a test file..!!"; file.close(); //close it } The fstream class is derived from the iostream classes, so ofstream variables can be used exactly how cout is used; through insertion (<<) operator. STEPS FOR READING FROM A FILE: 1. Declare an ifstream variable. 2. Open a file with it. 3. Read from the file (there are a couple of ways.) 4. Close it. Program 2: #include <fstream.h> void main(void) { ifstream file; file.open("file.txt"); //open a file char output[80]; //create a buffer while(!file.eof()) { file.getline(output,80); //write to it cout<<output<<endl; } file.close(); //close it } The fstream class is derived from the iostream classes, so fstream variables variables can be used exactly how cin is used; through extraction (<<) operator. Object Oriented Programming Lab # 7: OStreams Program to read character from file: #include <iostream> #include <fstream> using namespace std; int main() { char character; ifstream in_stream; ofstream out_stream; in_stream.open("Lecture_4"); out_stream.open("Copy_of_4"); in_stream.get(character); while (!in_stream.eof()) { cout << character; out_stream.put(character); in_stream.get(character); } out_stream.close(); in_stream.close(); } // read on a text file #include <iostream> #include <fstream> using namespace std; int main () { ifstream file1 ("watch.txt"); if (file1.is_open()) { char output[80]; while(!file1.eof()) { file1.getline(output,80); cout<<output<<endl; }} else cout << "Unable to open file"; file1.close(); return 0; } LAB TASKS L9_P1. Write a program which takes any number from the user and save the table of that number in a file named “datatable.txt” L9_P2. Write a program which takes number input from the file “datatable.txt”, and prints the table on the screen. Learning Outcome: Student become familiar with the filing and streams. Student become familiar how to log data. Student become familiar how to recall saved data. LAB # 10 FUNCTION TEMPLATES AND CLASS TEMPLATES OBJECTIVE: To write code for generic classes and functions i.e. independent of data types. THEORY: Templates are a way of making your classes and functions more abstract by letting you define the behavior of the class without actually knowing what data type will be handled by the operations of the class or a function. Templates can be used in conjunction with abstract data types in order to allow them to handle any type of data. For example, you could make a template stack class that can handle a stack of any data type, rather than having to create a stack class for every different data type for which you want the stack to function. The ability to have a single class that can handle several different data types means the code is easier to maintain, and it makes classes more reusable. FUNCTION TEMPLATES: Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class with out repeating the entire code for each type. In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function. These function templates can use these parameters as if they were any other regular type. Based on the argument types provided in the calls to function, the compiler automatically instantiates separates object code functions to handle each type of call appropriately. The format for declaring function templates with type parameters is: template<class AnyType> AnyType functionName (AnyType arg1, AnyTypearg2, …argn) { //Function’s code here } For example, to create a template function that returns the sum of two numbers, we could use: Program 1: #include <iostream.h> int add (int a, int b) {return a+b;} double adddouble (double a,double b) {return a+b;} main () {int a = 10; int b = 20; double c = 10.5; double d = 10.5; cout<< add(a,b) <<endl; cout<< adddouble(c,d) <<endl; } Out Put: #include <iostream.h> template<class T> T add (T a, T b) { return a+b;} main () {int a = 10; int b = 20; double c = 10.5; double d = 10.5; cout<< add(a,b) <<endl; cout<< add(c,d) <<endl; } Out Put: To create a template function that returns the Greater from two parameters, we could use: Program 2: #include <iostream.h> #include <iostream.h> int Large(int n1, int n2){ template<class T> return (n1>n2) ? n1:n2;// ternary conditional T Large(T n1, T n2){ operator} return (n1>n2) ? n1:n2;// ternary float Large(float n1, float n2){ conditional operator} return (n1>n2) ? n1:n2;} main () { int Large(char n1, char n2){ int i1, i2; return (n1>n2) ? n1:n2;} float f1, f2; main () { char c1, c2; int i1, i2; cout<<"Enter two integers: "; float f1, f2; cin>>i1>>i2; char c1, c2; cout<<Large(i1, i2)<<" is cout<<"Enter two integers: "; larger."; cin>>i1>>i2; cout<<"\n\nEnter two cout<<Large(i1, i2)<<" is larger."; floating-point numbers: "; cout<<"\n\nEnter two floating-point numbers: cin>>f1>>f2; "; cout<<Large(f1, f2)<<" is cin>>f1>>f2; larger."; cout<<Large(f1, f2)<<" is larger."; cout<<"\n\nEnter two characters: cout<<"\n\nEnter two characters: "; "; cin>>c1>>c2; cin>>c1>>c2; cout<<Large(c1, c2)<<" has larger ASCII cout<<Large(c1, c2)<<" has value.";} larger ASCII value.";} Out Put: Out Put: In this case, we have used T as the template parameter name instead of AnyType because it is shorter and in fact is a very common template parameter name. But you can use any identifier you like. In the example above we used the function template add() twice in main (). The first time with arguments of type int and the second one with arguments of type double. The compiler has instantiated and then called each time the appropriate version of the function. CLASS TEMPLATES: We also have the possibility to write class templates, so that a class can have members that use template parameters as types. For example: Program 3: #include <iostream.h> template<class T> class PrimitiveType { private: T x; public: PrimitiveType(T a=0) { x=a;} T getValue () {return x;}}; main () { PrimitiveType<int>i1(20); cout<< i1.getValue() <<endl; PrimitiveType<float>f1(20.9483); cout<< f1.getValue() <<endl; } Out Put : PrimitiveType class is a generic class which can be used to imitate the functionality of any primitive data type such as int, float, double, long etc. LAB TASKS L10_P1. Write template function for calculator operations. L10_P2. Write any program using template class. Learning Outcome: Student become familiar with the function template and class template. Student become familiar with the making and utilization of templates. LAB # 11 POINTERS OBJECTIVE To understand the concept of pointers and how to use them. THEORY When writing a program, you declare the necessary variables that you will need in order to accomplish your work. When declaring variables, you are simply asking the computer to reserve a set amount of space in its memory for a particular object you want to use. When you declare a variable, the computer reserves an amount of space for that variable, and uses the variable's name to refer to that memory space. This will allow you to store something, namely the value of that variable, in that space. Indeed, the computer refers to that space using an address. Therefore, everything you declare has an address, just like the address of your house. You can find out what address a particular variable is using. This address can be accessed by using pointers. Pointer is a variable that holds the address. To see a variable's address, you can use the “&” operator followed by the name of the variable. For example, after declaring an integer as int number; You can find the address where the number variable is located by using: cout << &number; This program_1 would give you the address of the declared variable: #include <iostream> using namespace std; int main() { int value; cout << "Value lives at " << &value; cout << "\n\n"; return 0; } All data types and structures can have pointers. Some commons applications of pointers are: Accessing array elements Passing arguments to a function when the function needs to modify the original argument Passing arrays and strings to functions Returning arrays and strings from functions Instead of referring to a variable's address directly, you are allowed to declare another variable, and then use that new variable to refer to the address of the variable you are interested in. A pointer is a variable that refers to another variable's address. Just like any variable in C++, you should declare and initialize a pointer variable before using it. To declare a pointer variable, use an identifier, followed by an asterisk (*), followed by the name of the pointer, and a semi-colon. Here is the formula: DataType * PointerName; The identifier should be one of those we have learned already. This means it could be an int, a char, a double, etc. The identifier should be the same type of identifier the pointer variable will point to. Therefore, if you are declaring a pointer that will point to an integer variable, the pointer identifier should be an integer. The asterisk (*) lets the compiler know that the variable that follows is a pointer. Program 2: This simple program creates a pointer variable ‘p’, assigns the address of ‘t’ to ‘p’, and prints the address of ‘p’, the address pointed by ‘p’ and the value pointed by ‘p’. Out Put: #include <iostream.h> main(void) {int *p; //declaration int t=200; p=&t; // the address of t is assigned to p cout<< p <<endl; // prints the value of 'p'(address of 't') cout<< &t <<endl; cout<< *p <<endl; // prints the value pointed by 'p' } Once you have declare a variable and assign it to a pointer, during the course of your program, the value of a variable is likely to change, you can therefore assign it a different value: Program 3: #include <iostream> using namespace std; int main () { int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << '\n'; cout << "secondvalue is " << secondvalue << '\n'; return 0;} Operations on Pointers: A pointer is a variable like any other: it can get its value from the user (indirectly), you can apply any of the algebraic operations we have learned, it can be incremented, it can be applied on a function, etc. A variable is a value that is supposed to change some time to time. Since a pointer is a variable whose value points to another variable, the value of a pointer is affected by the variable it points to. You can use this indirection to change the value of a pointer when changing its main variable. To get a value from the user, we have already learned that you can use the cin operator. When using a pointer to get a value from the user, don't forget the * operator, otherwise, the compiler would get confused. We have already learned how to request and display the value of a regular variable from the user. In the same way, you can request a value from the user and store it in the pointer. To see an example check Program 4. Program 4: #include <iostream> using namespace std; int main() { int students; int *ptrStudents; ptrStudents = &students; cout << "Number of students: "; cin >> students; cout << "\nNumber of students: " << *ptrStudents<<endl; return 0; } We have learned how to perform algebraic calculations and expressions in C++.When performing these operations on pointers, remember to use the * for each pointer involved. The calculations should be as smooth: Program 5: #include <iostream> using namespace std; int main() { int boys,girls,total; int *ptrBoys; int *ptrGirls; int *ptrTotal; ptrBoys = &boys; ptrGirls = &girls; ptrTotal = &total; cout << "Enter Number of male students: "; cin >> *ptrBoys; cout << "Enter Number of female students: "; cin >> *ptrGirls; total = boys + girls; *ptrTotal = *ptrBoys + *ptrGirls; cout << "\n\nTotal number of students: " << total; cout << "\nThere are " << *ptrTotal << " students"; cout << "\n\n"; return 0;} To Pass As A pointer in function: PROGRAM 6: #include<iostream.h> int add(int *a,int *b) {return *a+*b;} main(){ int x=100,y=200; cout<<add(&x,&y)<<endl;} POINTERS AND ARRAYS: Pointers are the variables that hold address. Pointers can point at cells of an array not only single variable. Consider this example: int* ptr; int a[5]; ptr = &a[2]; // &a[2] is the address of third element of a[5]. PROGRAM 7: #include <iostream> using namespace std; int main() { int a[5]; cout << "Enter 5 numbers: "; for (int i = 0; i < 5; ++i) { cin >> *(a+i) ;} cout << "Displaying data: " << endl; for (int i = 0; i < 5; ++i) { cout << *(a+i) << endl ; }return 0;} LAB TASKS L11_P1: Implement a program that swap two numbers using pointer? Learning Outcomes: Student become familiar with the concept of pointer in programming. Student become familiar with the utilization of pointer. Lab # 12 Introduction to Python Python Programming Python is a very powerful high-level, object-oriented programming language. Guido van Rossum is the creator of Python with its first implementation in 1989. Python has a very easy-to-use and simple syntax, making it the perfect language for someone trying to learn computer programming for the first time. Python is an interpreted language. Interpreter is a program that converts the high-level program we write into low-level program that the computer understands. Type the following text at the Python prompt and press the Enter: >>> print "Hello, Python!"; If you are running new version of Python, then you need to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result: Hello, Python! Python Identifiers A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier starts with a letter A to Z or a to z, or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python. Here are naming conventions for Python identifiers: Class names start with an uppercase letter. All other identifiers start with a lowercase letter. Starting an identifier with a single leading underscore indicates that the identifier is private. Starting an identifier with two leading underscores indicates a strongly private identifier. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name. Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example: Output We use the print() function to output data to the standard output device (screen). We can also output data to a file, but this will be discussed later. An example use is given below. >>> print('This sentence is output to the screen') This sentence is output to the screen >>> a = 5 >>> print('The value of a is',a) The value of a is 5 Input Up till now, our programs were static. The value of variables were defined or hard coded into the source code. To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is input([prompt]) >>> num = input('Enter a number: ') Enter a number: 10 >>> num '10' Import When our program grows bigger, it is a good idea to break it into different modules. A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py . >>> import math >>> from math import pi >>> math.pi >>> pi 3.141592653589793 3.141592653589793 ASSIGNMENT: Design a Bio-data program, which take input from user and finally display in the form of BIO-DATA. Learning Outcome: Student become familiar with the basics of Python programming language. Student become familiar with the environment of Python IDE. LAB # 13 Python with Mathematical function and User define Function Python Program to Make a Simple Calculator # define functions def add(x, y): """This function adds two numbers""" return x + y def subtract(x, y): """This function subtracts two numbers""" return x - y def multiply(x, y): """This function multiplies two numbers""" return x * y def divide(x, y): """This function divides two numbers""" return x / y # take input from the user print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input") Python Program to Display the multiplication Table: # Python program to find the multiplication table (from 1 to 10) of a number input by the user # take input from the user num = int(input("Display multiplication table of? ")) # use for loop to iterate 10 times for i in range(1,11): print(num,'x',i,'=',num*i) ASSIGNMENT: Design a program of low pass filter which shows cut off frequency value by taking inputs of Resistance and Capacitance values from User? Design a program of Band pass filter which shows resonance frequency value by taking inputs of Inductance and Capacitance values from User? Learning outcomes: Student become familiar with the User define function. Student become familiar how to implement mathematical function in Python. LAB #14 PYTHON WITH MATRICES Python offers a range of compound datatypes often referred to as sequences. List is one of the most frequently used and very versatile datatype used in Python. Creating a List In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. It can have any number of items and they may be of different types (integer, float, string etc.). A list can even have another list as an item. These are called nested list. # empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed datatypes my_list = [1, "Hello", 3.4] # nested list my_list = ["mouse", [8, 4, 6]] Accessing Elements in a List There are various ways in which we can access the elements of a list. Indexing We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4. Trying to access an element other that this will raise an IndexError . The index must be an integer. We can't use float or other types, this will result into TypeError . Nested list are accessed using nested indexing. >>> my_list = ['p','r','o','b','e'] >>> my_list[0] 'p' >>> my_list[2] 'o' >>> my_list[4] 'e' >>> my_list[4.0] ... TypeError: list indices must be integers, not float >>> my_list[5] IndexError: list index out of range >>> n_list = ["Happy", [2,0,1,5]] >>> n_list[0][1] # nested indexing 'a' >>> n_list[1][3] # nested indexing 5 Negative indexing Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. >>> my_list = ['p','r','o','b','e'] >>> my_list[-1] 'e' >>> my_list[-5] 'p' Slicing We can access a range of items in a list by using the slicing operator (colon). >>> my_list = ['p','r','o','g','r','a','m','i','z'] >>> my_list[2:5] # elements 3rd to 5th ['o', 'g', 'r'] >>> my_list[:-5] # elements beginning to 4th ['p', 'r', 'o', 'g'] >>> my_list[5:] # elements 6th to end ['a', 'm', 'i', 'z'] >>> my_list[:] # elements beginning to end ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z'] Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need two index that will slice that portion from the list. Deleting or Removing Elements from a List We can delete one or more items from a list using the keyword del . It can even delete the list entirely. >>> my_list = ['p','r','o','b','l','e','m'] >>> del my_list[2] # delete one item >>> my_list ['p', 'r', 'b', 'l', 'e', 'm'] >>> del my_list[1:5] # delete multiplt items >>> my_list ['p', 'm'] >>> del my_list # delete entire list >>> my_list Matrix Addition using Nested Loop and List # Program to add two matrices using nested loop X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) Assignment Design a matrix 3x3 by taking input from user and find the square of each element inside the matrix. Learning Outcome : Student become familiar how to create & manipulate matrices.