Unit - V
Unit - V
Unit - V
Introduction Kind of inheritance C++ inheritance and Class Scope Types of inheritance Virtual Base Class Pointers Pointers to Objects this Pointer Pointers to Base and the Derived Classes Virtual Functions Abstract classes Introduction to Files Opening and closing of files Random Access File Command Line Argument UNIX Shell Programming Basic Unix Commands Vi Editor Programming the Shell
5.0
Introduction
It is a fundamental aspect of human intelligence to seek out, recognize, and create relationships among concepts. We build hierarchies, matrices, networks, and other interrelationships to explain and understand the ways in which things interact. C++ attempts to capture this in inheritance hierarchies. Inheritance is a technique of organizing information in a hierarchical form. Typically, the pure virtual functions in an abstract base class are never implemented. Because no objects of that type are ever created, there is no reason to provide implementations, and the ADT works purely as the definition of an interface to objects which derive from it. Files are used to store information permanently and to retrieve it whenever required. The file handling techniques of C++ support file manipulation in the form of stream objects. UNIX is an increasingly popular operating system. Traditionally used on minicomputers and workstations in the academic community, UNIX is now available on personal computers, and the business community has started to choose UNIX for its openness.
5.1
Objective
The objective of this lesson makes the learner aware of the fundamentals of inheritance, pointers and files. The fundamental concepts include types of inheritance,
Page 113
5.2
5.2.1
Content
Inheritance One of the most useful features of classes is inheritance. It is possible to declare a class, which inherits the properties of another class or classes. This means that, with good class design, applications, which are based on proven re-usable code, can be built. Thus classes extend the feature of reusability of code, particularly complex code. Definition: Inheritance is the mechanism by which a new class inherits the members of an already existing class. Suppose a class A inherits the properties of a class B, it means A inherits from B. Objects of class A thus have access to attributes and methods of class B without the need to redefine them. If class A inherits from class B, then B is called superclass of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behaviour as objects of the superclass. In addition to the members inherited from the superclass, the subclass can also include additional members. Superclasses are also called parent classes. Subclasses may also be called child classes or just derived classes. The subclass can again be inherited, making this class the superclass of the new subclass. This leads to a hierarchy of superclass/subclass relationships. The general format for inheriting a class is: class new_class: access specifier existing_class { members; }; In this case, new_class is the name of the subclass that is to be created. access specifier can be either public, private or protected. existing class is the name of the superclass whose members are to be inherited by the subclass. members refer to the extra instance variables and functions that the subclass can include in addition to the members of its superclass. If a subclass inherits from more than one class then these classes along with an access specifier have to be separated by a comma ,. class new_class: access specifier existing_class1, access specifier existing_class2 Page 114
Page 115
Page 116
Page 117
Every class in C++ has its own individual scope even when it inherits members from other classes. Those members that are explicitly defined in the class definition of a derived class belong to the scope of that class, those members which are members in virtue of inheritance belong to the scope of the super-class from which they were inherited. The scope rules for C++ classes have a number of consequences. 1) Those member functions which belong to the scope of a derived class will only have access to the data members within the scope of the derived and to those data members which are inherited from the public or protected section of the super-
Page 118
The inheritances seen so far come under the category of single inheritance. There are five different types of inheritance namely: Single Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance
Single Inheritance In this type of inheritance a new class called the derived class inherits the members of a single class called the base class. There is only one level of inheritance. This means that the newly created class does not have any derived class and has only a single parent class. This is diagrammatically represented as:
class A
class B
Single Inheritance In this case class A is the super class of class B. Multi-level inheritance In this type of inheritance a new class called the derived class inherits the
Page 119
class A class B
class C
Multi-level inheritance In this case class A is the super class of class B, which in turn is the base class of class C. Multiple Inheritance In this type of inheritance a new class called the derived class inherits the members of more than one class. This is diagrammatically represented as follows:
class A
class B
class C
Multiple inheritance
In this case, class C inherits the members of both class A as well as class B. Thus class C has two parent classes.
Page 120
class A
class B
class C
Hierarchical inheritance In this case, two classes B and C inherit the members of class A. Hybrid Inheritance A combination of any two or more types of inheritance is called hybrid inheritance.
class C
Page 122
A potential problem for multiple inheritance occurs when a chain of inheritance derives from a single class via two or more paths, thus causing duplication of inherited data and functions.
As can be seen from the diagram, classes B and C inherit the member function fun() of class A using hierarchical inheritance. Class D inherits the members of class B and class C through multiple inheritance. Ultimately, class D will have 2 copies of the function fun()- one inherited from class B and the other inherited from class C. While Page 123
void main() { Child c; cout << c.getdata(); } Output: 1 The virtual keyword tells the compiler to inherit only one sub-object into subsequent derived classes. 5.2.3 Pointers
Pointers can be confusing and at times, one may wonder why one would ever want to use them. The truth is, they can make some things much easier. For example, using pointers is one way to have a function modify a variable passed to it; it is also possible to use pointers to dynamically allocate memory, which allows certain programming techniques, such as linked lists. Pointers point to locations in memory. Picture a big jar that holds the location of another jar. In the other jar holds a piece of paper with the number 12 written on it. The jar with the 12 is an integer and the jar with the memory address of the 12 is a pointer Pointer syntax can also be confusing, because pointers can both give the memory location and give the actual value stored in that same location. When a pointer is declared, the syntax is this: variable_type *name; Notice the *. This is the key to declaring a pointer and it is used before the variable name. There are two ways to use the pointer to access information about the memory address it points to. It is possible to have it give the actual address to another variable. To do so, simply use the name of the pointer without the *. However, to access the actual value in that particular memory location pointed by the pointer, use the *. The technical name for doing this is dereferencing. In order to have a pointer actually point to another variable it is necessary to have the memory address of that variable also. To get the memory address of the variable, put the & sign in front of the variable name. This helps in retrieving the address of that variable. This is called the reference operator, because it returns the memory address. Example #include <iostream.h> int main() { int x; int *pointer; Page 126
Page 127
ptrshow();
If a class has a constructor with arguments and does not include an empty constructor, one must supply the arguments when the object is created. Create an array of objects using pointers. For Example, the statement item *ptr = new item[10];//array of 10 objects create a memory space for an array of 10 objects of item. Remember, in such cases, if the class contains constructors, it must also contain an empty constructor. The following example illustrates the use of pointers to objects. One object is assigned to another object rather than passing the values as an argument. #include <iostream.h> class item { int code; float price; public: void getdata(int a, float b) { code = a; price = b; } void show(void) { cout << "Code : " << code << "\n"; cout << "Price : " << price << "\n"; } }; const int size = 2; main() { item *p = new item [size]; item *d = p; int x, i; float y; for(i=0;i<size;i++) { Page 129
The same function name is used in both the base and derived classes, the function in base class is declared as virtual using the keyword virtual preceding its normal declaration. When a function is made virtual, c++ determines which function to use at run time based on the type of objects pointed to by the base pointer, rather than the type of the pointer. When a virtual function is called from a pointer, the compiler does not always know what type of object the pointer is pointing to. In this case, it may not know which version of the function to call at compile time and this judgment is delayed until runtime. At runtime, when the function call is executed, the code finds out the type of object whose address is in the pointer and calls the appropriate function, depending on the class of the object. Static Binding As in traditional programming languages, the compiler calls fixed functions based on the code. The linker replaces the identifiers with a physical address. Essentially, all function calls are resolved at compilation itself. Connecting to the functions in the normal way at compilation is called early or static binding.
Page 133
Page 134
Page 135
Page 136
Page 137
Files are used to store information permanently and to retrieve it whenever required. The file handling techniques of C++ support file manipulation in the form of stream objects. A stream is a general name given to the flow of data in an input/output process. In fact cin and cout used so far are themselves stream objects. These stream objects are pre-defined in the header file iostream.h. Both cin and cout are used for standard input and output respectively. The extraction operator >> is a member of the istream class and the insertion operator << is a member of the ostream class. Both of these classes are derived from ios class. Disk files require a different set of classes than files used with standard input and output. C++ has two basic classes to handle files, ifstream and ofstream. ifstream handles file input (reading from files) and ofstream handles file output (writing to files). There is another class called fstream which can handle both input and output. All these classes are present in the header file fstream.h. Hence this header file has to be included for programs pertaining to disk file handling. The following diagram illustrates the stream class hierarchy.
Page 138
5.2.5.1 open()
The first operation generally done on an object of one of the stream classes is to associate it to a real file, that is to say, to open a file. The function used for this purpose is open(). The general syntax of open() is: void open (const char * filename, openmode); where filename is a string of characters representing the name of the file to be opened and openmode is a combination of the following flags: ios::in ios::out ios::ate ios::app ios::binary Open file for reading Open file for writing Erase file before reading or writing Every output is appended at the end of file Binary mode
The class ios is a virtual base class for the istream and ostream. The iostream(input and output stream) is a class with multiple inheritance from both istream and ostream. These flags can be combined using bitwise operator OR (|). For example, if a file "example.bin" is to be opened in binary mode to add data it can be written as follows: ofstream file; file.open ("example.bin", ios::app | ios::binary); Suppose no mode is specified, this function will directly open an already existing file in read mode when used with an object of ifstream and in write mode when used with an object of ofstream. The member functions open of classes ofstream, ifstream and fstream include a default mode when opening files that vary from one to other: Class ofstream ifstream fstream Default mode to parameter ios::out ios::in ios::in | ios::out
The default value is only applied if the function is called without specifying a mode parameter. If the function is called with any value in that parameter the default mode is stepped on, not combined. close()
Page 139
Page 140
#include <fstream.h> void main() { ofstream of; char c; of.open (abc.txt); cin>>c; while(c!= 0) { of << c; cin>>c; } of.close(); } The above program first accepts an input from the user. It checks if that character is not equal to zero. If it is not, it enters the while loop and writes that character into a file. This way, it accepts all the characters one by one and writes into the file until the user inputs a zero. Reading a text from a file The following program illustrates how to open a file, read its contents and display it on the screen. The program accepts a file name from the user. When the user supplies a file name, the program checks if such a file exists and the program exits if the file does not exist. The function fail() is used for this purpose and returns true if the file is not opened. //Reading the contents of a text file and printing it out #include <fstream.h> #include <iostream.h> #include <iomanip.h> #include <stdlib.h> void main() { ifstream infile; char fname1[20]; char ch; cout << "Enter the filename to be read \n"; cin >> fname1; infile.open(fname1); if (infile.fail()) {
Page 141
Page 142
The read() member function is used to get data for a stream of objects from a specified file. The following program segment depicts how to read objects belonging to a class using the read() function. //reading an object from a file #include <fstream.h> class emp_info { private: char name[30]; int age; public: void input_data() { cout<< "Enter the name"<<endl; cin>>name; Page 144
The knowledge of the logical location at which the current read or write operation occurs is of great importance in achieving faster access to information stored in a file. Thus a file in which any record can be accessed at random is called a Random Access file. C++ I/O system supports four functions for setting a file pointer to any desired position inside the file or gets the current file pointer. These functions allow the programmer to have control over the position at which the read or write operations take place. The seekp() and tellp() are member functions of class ofstream. The seekg() and tellg() are member functions of class ifstream. All these four are available in fstream. These functions can be used in manipulating the position of the stream pointers that point to the reading or writing locations within a stream.
Page 145
Page 147
They encapsulate their internal working from the user. The programmer need not specify the type of data to be input or output. It is determined automatically by the stream class. 5.2.6 Command line arguments
In C++ it is possible to accept command line arguments. To do so, one must first understand the full definition of int main (). It actually accepts two arguments, one is the number of command line arguments and the other is a listing of the command line arguments. It looks like this: int main(int argc, char* argv[]) The integer argc, is the Argument Count (hence argc). It is the number of arguments passed into the program from the command line, including the path and name of the program. The array of character pointers is the listing of all the arguments. argv[0] is entire path to the program including its name. After that, every element numbers less than argc are command line arguments. One can use each argv element just like a string or use argv as a two dimensional array. #include<iostream.h> void main(int argc,char* argv[]) { cout<<" Argc: " <<argc; for(int i=0;i<argc;i++) cout<<" Argv: " <<argv[i]; } Output :( when run in dos prompt) writefile 4 pop 45 67 Argc: 5 Argv: C:\BC5\BIN\WRITEFILE.EXE Argv: 4 Argv: pop Argv: 45 Argv: 67 Where writefile is the name of the file.
Page 148
Example
$ ls abc file xyz cd command This command is used to change from current directory to another directory.
Example
$ cd /bin
Page 149
Example
$ mkdir Abc pwd command This command returns the present working directory of the user
Example
$ pwd /usr/student cp command This command is used for making a copy of a file
Example
$ cp s d This command copies the content in file s to a new file called d. The file s remains unchanged. mv command This command is used for renaming a file
Example
$ mv s d This command renames the file s to a new file called d. rm command This command is used for removing a file.
Example
$ rm s This command deletes the file s.
Page 150
Example
$ rmdir abc This command removes the directory abc. 5.2.8 Vi Editor
Information can be entered in file using cat command. One disadvantage in this is that if the content has to be modified, the entire file content has to be retyped. This disadvantage is overcome in the case of vi editor. vi stands for Visual. is an editor which has a command mode and a typing mode. To open a file using vi, the command vi is followed by the filename. To enter the text in it the mode has to be changed to insert command i. When ever the mode has to be changed, escape button has to be hit. One important aspect of vi is that it does not provide the original copy of the file when invoked. It provides a Editing Buffer. All changes are done to that copy in the buffer. The original file is replaced when the user quits vi. vi functions in three different modes. They are: Command Mode Insert Mode Ex escape Mode
vi
In the command mode, any key pressed by the user is assumed as commands of the editor. No text is displayed on the screen when any key is pressed. The insert mode helps to insert the text into the vi editor. This mode can be invoked by using any of the insert, open or append mode command. The ex escape mode is introduced to make the vi and the ex editors compatible. When any command is typed in this mode it is shown on the command line. The bottom line of the vi screen is called as the command line. Here messages are displayed and all commands entered in the ex escape mode are displayed. vi emits a beep sound if there is any error. The vi editor can be invoked by typing vi at the $ prompt. vi can be invoked with a filename. The syntax is $ vi filename Usage of General vi Commands The usage of general vi commands is as follows: a. Getting Started with vi
Page 151
b. Movement of the Cursor All vi commands involve alphabets and the shift and control keys. Since vi is case sensitive, the user must make sure that the Caps lock is off. The cursor movements can be described as follows: Keys h or backspace l or space bar k or j or + Directions Left Right Up Down
Page 152
Functions
Moves forward by a word. Assumes that punctuations are next words. Moves forward by a word and this identifies punctuations as a part of the word. Takes the cursor to the last character of the word. Takes the cursor to the last character of the word and ignores any punctuation. Moves backward by a word. Moves backward by a word and ignores any punctuation. Takes the cursor to the beginning of the line. Takes the cursor to the end of the line. Takes the cursor to the last line of the file. Works like the GOTO command. For e.g to go to the second line in the file the user can say 2G.
Some more examples of the above movements are: 2w (will move the cursor by two words) 4$ (end of the fourth line) 5b (move five words back) d. Screen Commands The table below lists few of the commands used to traverse the screen. Keys Ctrl + F
Functions
Moves forward by a screen. To have continuity the last two lines of the previous screen are displayed. Ctrl + B Moves backward by a screen. Here again two lines of the previous screen are displayed. Ctrl + D Moves the cursor half the screen forward. Ctrl + U Moves the cursor half the screen backward. Ctrl + L To clear any message that vi has displayed or to clear any system messages that appear on the screen. Ctrl + G Displays the status on the status line. Gives the name of the file that is edited, the number of lines in the file, the current line number and the percentage of file that precedes the cursor. e. Usage of some Editing
Page 153
Functions
Invokes insertion mode. Text insertion is possible only after invoking the insert mode. The capital I invokes the insert mode and insertion takes place at the beginning Allows insertion by creating a blank line above the current line Allows insertion by creating a blank line below the current line Used for appending the text .Text is appended after the current position Used for appending the text. Text is appended at the end of the line.
Deleting text in vi
If the user wants to delete a character or a word or a line that the user typed, use the following delete commands. Keys dd ndd dw dW D x X nX
Functions
Deletes the line in which the cursor is positioned Deletes n Lines Deletes the word from the cursor position to the end of the word. It stops at any punctuation that appears in the word Deletes the word from the cursor position to the end of the word. It ignores any punctuations that appear with the word Deletes the line from the current cursor position to the end of the line Deletes current cursor position Deletes back one character Deletes previous n characters
h. The undo Command In case, the user deleted a word or a line by mistake and the user wants the same, then the undo command is used. To use the undo command, ensure to be in the command mode and then press u. i. Joining lines of Text
Suppose the user wants to join any two lines of the text, then the user can make use of the J command. To join any two lines, place the cursor at the end of the first line and then press the letter J.
Page 154
Shell scripts and C programs are written using the vi editor. The programs and coding may be very long. If the user wants to go to the fifth line of the Shell script or the C program, it is better to have the text numbered. vi offers the facility of numbering text. In order to utilize this facility, the user must ensure the command mode. Then press : to specify that the command is in the escape mode. As soon as the user presses colon, he is taken to the command line of the vi editor. Now type the command as given below: (Esc) : set number
Line numbers are then set and all the lines are arranged sequentially. If the user deletes a line, the line numbers are changed automatically. If the user does not want the numbering to be done, then the following command is given. (Esc) : set nonumber The users working mode can be identified by the set showmode command, which is executed like the set number command. (Esc) : set showmode k. Changing Text The following commands are used to change the text. Keys Cw Cc C P p Rx Rtext S Ns S u U l.
Functions
Change word Change Line Change text from current position to end of line Insert last deleted text after cursor Insert last deleted text before cursor Replace character with X Replace text beginning at cursor Substitute character Substitute n characters Substitute entire line Undo last changes Restore current line
In order to make use of these facilities, the user must ensure the command mode. These multiple lines depend on three major commands. They are: Copy to the desired position Move to the desired position Page 155
Copy to the Desired Position The user can copy a single line or block of lines to the desired lines.
Example 1 Suppose the user wants to copy the second line in the file below the fifth line then, (Esc) : 2 co 5 Example 2 If the user wants to copy the first three lines below the seventh line, then do the following (Esc) : 1,3 co 7 n. Move to the Desired Position
The user can move the lines in a file to the desired position using the following commands. To move the third line of the file to the ninth line of the file, the command is as follows (Esc) : 3 mo 9 A range of lines can be moved to the desired position. Example If the user wants to move the fourth line and seventh line of a file to the end of the file, then (Esc) : 4 , 7 mo $ o. Delete desired number of lines
It is possible to delete multiple lines in a single command using the escape command. Example The user can delete the fifth line to the seventh line in a file, using the command (Esc) : 5,7 d
Page 156
5.2.9
A shell is a program that acts as an interface between the kernel and the user. For example, when the user types in a program at the unix prompt, the shell searches the PATH for the occurrence of that program name, then the shell instructs the kernel to load the program, push the program parameters supplied at the command line onto the stack and finally make the instruction pointer point to the entry point of the program and then finally execute the program. Shell program is primarily used to automate routine systems administration duties. Shell Scripts
Page 157
Example
The example compares two strings, if the two strings are equal then the message The strings are equal are displayed else the message the strings are not equal is displayed.
Page 158
Example
echo `date` hour=`date|cut -c12-13` echo $hour if [ $hour -gt 0 -a $hour -lt 12 ] then echo "Good Morning" elif [ $hour -gt 12 -a $hour -lt 14 ] then echo "Good Afternoon" else echo "Good Evening" fi Page 159
Example
In this program, lower case alphabet is accepted as input and checked whether it is a vowel or not. echo "Enter a character" read a case $a in a) echo "It is a vowel";; e) echo "It is a vowel";; i) echo "It is a vowel";; o) echo "It is a vowel";; u) echo "It is a vowel";; *) echo "Not a vowel";; esac Output: $sh s38 Enter a character a It is a vowel $sh s38 Enter a character q Not a vowel The for Construct
Page 160
Example
The following program prints 5 stars 5 times. for i in 1 2 3 4 5 do echo "*****" done
Output:
***** ***** ***** ***** *****
The while Loop The statements within the while loop are executed repeatedly as long as the condition remains true The syntax for the while loop is: while control command do commandlist done Each time the shell attempts to execute the control command, if the exit status of control command is a Zero, that is, success, then the commands between do and done are executed.
Example
The following program is for printing the factorial of a number. echo "Enter a number" Page 161
Example
The following program prints numbers from 1 to 9. a=1 until [ $a -eq 10 ] do echo $a a=`expr $a + 1` done
Output:
1 2 3 4 5 6 7 Page 162
Example
The following shell scripts checks if an argument string contains anything so that the script will stop executing if the argument string is empty. if test $# = 0 then echo Error no arguments entered exit fi The shift Command The maximum number for positional parameters can be $9. The user can use the argument $1 through $9 in the shell script at a time. Suppose if more than nine number of positional parameters, then the shift command is used. The shift command discards the first argument and renumbers the rest. The following example uses shift command to display a pyramid of the command line argument. Example The following program has to be executed with command line argument as 1 2 3 4 5. for n in 1 2 3 4 5 do Page 163
5.3
Revision Points
Inheritance The technique of building new classes from the existing classes is called inheritance. Single Inheritance Derivation of a class from only one base class is called single inheritance. Multiple Inheritance Derivation of a class from several (two or more) base classes is called multiple inheritance. Pointers A pointer is an entity, which contains a memory address. this pointer Using this pointer, any member function can find out the address of the object of which it is a member. It can also be used to access the data in the object it points to. Dynamic Binding It is a process in which function calls are resolved at runtime. Static Binding It is a process in which the identifiers are associated with the physical address during the process of compilation and linkage. Virtual Function
Page 164
5.4
Intext Questions
1. What does inheritance mean in C++? 2. Describe the syntax of multiple inheritance. When is the inheritance used? 3. What is virtual Base class? 4. When the class is made virtual? 5. Explain any five basic UNIX commands. 6. Explain this pointer with an example. 7. Explain pure virtual function with an example. 8. Explain command line argument with an example. 9. Write a note on reading and writing text to a file 10. Write a note on stream class hierarchy
5.5
Summary
Inheritance is the mechanism that allows a class A to inherit properties of another class B. The class from which a new class inherits is called the Super Class and the newly created class is called Derived Class. A new class can inherit the members of a base class in public, protected or private modes. Single inheritance is the mechanism by which a class inherits the members of only one class. Multiple inheritance is the mechanism by which a class inherits the members of more than one class. Pointer is a variable that can hold the address of another variable. Operators used in Pointers are & and *. & means Address Of. * means Value at. A pointer can point to an object created by a class. The arrow operator (->)is used to access the member of that class. This is called pointer to objects.
Page 165
Object can be written into a file using the functions read() and write(). A random access file helps in accessing a particular record. Date command displays the current date and time. who command tells which user is currently using the system. ls is the program to list files in a directory. cd command is used to change from current directory to another directory. vi is an editor which has a command mode and a typing mode. A shell is a program that acts as an interface between the kernel and the user.
5.6
Terminal Exercises
Page 166
1. Inheritance helps in making a general class into a more specific class? (True/False). 2. A base class is never used to create objects? (True/ False). 3. What is the open() command? 4. Write a note on shell programming. 5. Write a note on different loops supported by UNIX.
5.7
Supplementary Materials
1. Schildt, C++: The Complete Reference, Third Edition, TMH, 2000. 2. Sumitabha Dass, Unix Concepts and Applications, Second Edition, TMH, 1998 3. E.Balagurusamy, C++, Second Edition, TMH, 2001.
5.8
Assignment
1. Define class person (A person has a name, address, telno, email, DOB etc). Extend that class to define a classes called Official, Student; Staff each of them having specific properties. Implement virtual functions for getting details and calculating the performance. 2. Write a program that creates a file called Info.txt to write a string into it. 3. Write a program that reads the content of a file that has the following content. Reading the information from the file 4. Write a program that writes an object of a class into a file and reads the same. 5. Write a shell program to display an output as follows 1 12 123 1234 12345 6. Write a shell program to print the greater of two numbers.
5.9
Page 167
5.11 Keywords
Inheritance Virtual function File Write () Date ls mkdir cp rmdir Pointer Abstract class read () Shell who cd pwd mv rm
Page 168