02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the...

80
©NIIT Object-Oriented Programming 1 R ATIONALE Why This Module? Object-Oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object orientation help the developer to use such languages more effectively. C++ is the language of choice for object oriented programming (OOP) as the C++ language was developed to implement the concepts of OOP. The results of the feedback from the industry survey done by NIIT (refer to the slide below) point towards maximum weightage given to a fresher who has solid fundamentals in basic software engineering concepts. Software engineering (productivity,adapting to the changing requirement ) Fundamentals and concepts (uncertain technology demands strong concepts) Key technologies (SDLC,SQA,V&V METHODS coding stds.,documentation stds.) DBMS,O/S,OOM,Architecture,e-comm. 100% 80% 50% W e ig h ta g e g i v e n to a f r e s h e r Survey Findings 50% weightage is given to a fresher who has good knowledge of the basic concepts of software engineering and development. Therefore, there is a conscious focus of moving from a “Key technologies” focus (Top to bottom) to a “Fundamentals and concepts” focus which is in sync with the formal education system and industry requirements.

Transcript of 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the...

Page 1: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 1

RATIONALE

Why This Module? Object-Oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object orientation help the developer to use such languages more effectively.

C++ is the language of choice for object oriented programming (OOP) as the C++ language was developed to implement the concepts of OOP.

The results of the feedback from the industry survey done by NIIT (refer to the slide below) point towards maximum weightage given to a fresher who has solid fundamentals in basic software engineering concepts.

Software engineering(productivity,adapting to the changing requirement)

Fundamentals and concepts (uncertain technology demands strong concepts)

Keytechnologies

(SDLC,SQA,V&V METHODScoding stds.,documentation stds.)

DBMS,O/S,OOM,Architecture,e-comm.

100%

80%

50%

Wei

ghta

ge g

iven

to a

fres

her

Survey Findings

50% weightage is given to a fresher who has good knowledge of the basic concepts of software engineering and development.

Therefore, there is a conscious focus of moving from a “Key technologies” focus (Top to bottom) to a “Fundamentals and concepts” focus which is in sync with the formal education system and industry requirements.

Page 2: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

2 Object-Oriented Programming ©NIIT

Software engineering(productivity,adapting to the changing requirement)

Fundamentals and concepts (uncertain technology demands strong concepts)

Keytechnologies

(SDLC,SQA,V&V METHODScoding stds.,documentation stds.)

DBMS,O/S,OOM,Architecture,e-comm.

SURVEY CONCLUSIONSurvey Findings

T OP

2 B

OTT

OM

FO

CU

S

BO

T TO

M 2

TO

P F

OC

US

This module on object-oriented programming, covers all the concepts associated with OOP and implements the concepts learnt using C++. Every session in this module first covers the concepts and then the related implementation using C++.

Page 3: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 3

OBJECTIVES Besides introducing students to the fundamentals of OOPS, this module will familiarize them with the following:

Report data

Access data using pointers

Create classes and objects

Overload functions

Relate classes in C++

Overload operators

Store and retrieve file data

Implement late binding

Implement single linked lists

Implement stacks using linked lists

Implement queues using linked lists

At the end of the OOPS module, the student should be comfortable with the basic concepts of OOPS and also be able to effectively use C++ as an object-oriented programming language.

Page 4: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

4 Object-Oriented Programming ©NIIT

ENTRY PROFILE A student who registers for the OOPS module should be able to perform the following tasks:

Build flowcharts and write pseudocode – The student should be able to represent logic and sequence tasks for execution involving conditional operations and iterations. This will be essential for C++ programming.

Work in the Linux environment – The student should be able to create files, navigate directories, and use an editor in Linux.

Work in a Windows environment – The student should be able to navigate in a Windows environment.

Create and maintain documents – The student should be able to use an editor and perform simple editing tasks.

Interact in English in a classroom environment – The course is conducted in English and the courseware is written in English. The classes are meant to be interactive in nature.

Page 5: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 5

EXIT PROFILE At the end of this module, the student will be able to:

Design an object-oriented application.

Write applications that can dynamically accept data from user using the given data structures linked lists, stacks and queues.

Write applications that can write and read from the file.

Skills Acquired

Compile a C++ program

Execute a C++ program

Create and use arrays and pointers

Create classes

Code methods of a class

Declare objects

Pass arguments to functions

Identify relationships

Represent relationships in a C++ program

Override methods of a base class in the derived class

Use virtual and pure virtual functions

Overload operators

Write data to a file

Create and use linked lists, stacks and queues

Apply the different sorting methods

Page 6: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

6 Object-Oriented Programming ©NIIT

FAQ Q.1. Can the public member variables and functions of a class be used in another class or

function that has been defined in a different program file?

A.1. Yes, but the class declaration must be included in the first.

Q.2. What is the difference between '//' and '/* ... */' ?

A.2. Double slashes ‘//’ define comment entry for a single line whereas ‘/*…..*/’ marks a block as a comment entry.

Q.3. What is the difference between compilation and linking?

A.3. In compilation the compiler translates a program written in a high-level language like C++ into machine language also called the object code. Linking combines the source object code with the object code of the pre-defined functions that you are using in your program and adds some standard startup code to produce a run-time version of your program. At the end of this step, a file containing the executable code is produced.

Q.4. What is endl and how is it different from '\n' ?

A.4. The endl manipulator and the newline character places the cursor in the next line. The following two statements will display the strings, "hello" and "bye", on two different lines on the screen.

cout << "hello" << endl << "bye"; cout << "hello\nbye";

Q.5. What is the difference between " " and ' '?

A.5. A string is represented as a group of characters enclosed within " ". A single character is enclosed within ' '.

Q.6. What is the difference between '>>' and getline()?

A.6. For the answer please refer to pages 10.7 and 10.9 of the OOP’s Student Guide.

Q.7. If a class has a constructor defined within it, is it necessary that it should also define a destructor for the class?

A.7. No.

Q.8. Can I use functions from two different libraries in the same program?

A.8. Yes, provided there are no duplicate symbols in the libraries.

Q.9. What is the importance of the scope resolution operator?

A.9. The scope resolution operator is used to refer to the global variables in a program and can also be used to refer to the public member variables of the Base class.

Q.10. What is the difference between public, private, and protected inheritance?

A.10. The public members of a class can be accessed anywhere in the application. The private members of a class can be accessed only by the member functions of that class. And the

Page 7: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 7

protected members of a class are accessible to the member functions of that class, and the member functions of the classes derived from it.

Q.11. Can the protected access specifier be used without inheritance?

A.11. Yes.

Q.12. What is the difference between the while loop and the do...while loop?

A.12. Program enters the loop atleast once in case of do…while. Whereas, if the condition is not met the program does not enters the loop for while.

Q.13. How can a list be sorted on two fields?

A.13. A list can be sorted by having two pointers in a node structure, with both pointers pointing towards two different nodes. For example:

struct Node {

string Field1, Field2; Node *nextField1, *nextField2; Node(const string &f1, const string f2, Node *n1 = NULL, Node *n2 = NULL) : Field1(f1), Field2(f2), nextField1(n1), nextField2(n2)) { }

};

Page 8: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

8 Object-Oriented Programming ©NIIT

LESSON SPECIFIC INPUTS

Lesson One

Experiences You can start this session by talking about the complexity of the software system. The reasons for the complexity of the software system should be stated and explained. Briefly explain how this complexity can be simplified using the example of a PC.

The concept of objects and classes should be introduced with the help of examples from daily life and then software-related terms may be introduced. A situation can be given to students and an exercise on identifying objects and classes may be carried out.

Students should be made to understand the benefits of the object-oriented approach.

While explaining analysis and design to students, you must make them realize the importance of these phases taking the example of the Boeing factory.

You should stress on the rules and conventions followed while naming classes.

Examples and Analogies While explaining the need for functions, you can talk about the evolution of programming languages. You could tell students that earlier the programs used to be monolithic in nature, then the modular approach was adopted, followed by the object oriented way of programming.

C++ is a hybrid programming language that supports both the modular and object-oriented way of programming. At this point, you could also draw a comparison between C++ and Java. Additionally, you could make a point that C++ supports stand-alone functions because it is a hybrid programming language.

Based on the profile of the batch, you could take the discussion further and tell students that the software personnel across the world are always on the look-out for more efficient ways of writing programs.

FAQ Q.1. Where is the cout object defined?

A.1. In the header file, iostream.h.

Q.2. What is the difference between C and C++?

A.2. There are many differences, but the most important ones are as follows:

The C language does not have the concept of a class.

C structures cannot have member functions or private members.

Page 9: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 9

C does not allow variables to be defined any-where in the code other than the beginning of a block.

Q.3. Why are we not learning C in this semester?

A.3. C++ is used more than C nowadays. C++ is more versatile and can be used for a larger number of applications than C. C++ is a superset of C.

Q.4. Can a C++ program run on a Windows platform?

A.4. Yes. A Windows specific compiler like the Visual C++ and DJGPP GUI compiler will compile C++ programs and allow it to run on Windows.

Q.5. Do we need to know C before learning C++?

A.5. No. This course teaches C++ from the ground up.

Just a Minute…

Jane has called a technician to repair her television. How would the technician deal with the complexity of the television?

Solution: The television is a complex system. It would be impossible and thus meaningless to understand its comprehensive functioning, at one go. Thus, the technician would concentrate on the different parts of a television and understand their respective functions and the problems that are likely to occur in each one of them. For example, the technician might first inspect if the antenna for the television is positioned appropriately. Then, he might inspect the picture tube of the television.

Just a Minute…

Identify the possible attributes to define the state of the following objects:

a. Teacup

b. Stereo tape-recorder

Solution:

Attributes of a teacup: the dimension, the material with which the cup is made,and the color(s) used in the cup.

Attributes of a stereo tape recorder: the dimensions and sound output.

Just a Minute…

Dr. James and Mr. Hyde went to the railway station to book two tickets in the Flying express for 3rd December by AC 1st class. Identify the following:

a. The possible receiver of the message in this situation

b. The possible method that the receiver can use

Page 10: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

10 Object-Oriented Programming ©NIIT

Solution:

a. The receiver of the message here would be the clerk sitting behind the counter.

b. The clerk would check if two tickets are available on the train in the desired class, on the desired date. If they are, the clerk would enter the details (either he would put down the details of name, age, date, seat, berth numbers, etc, in a register or feed it in the computer) confirming the reservation of two tickets, and collect the fare.

Just a Minute…

State whether the following situations demonstrate reusability:

a. Recycling paper

b. Pump reusability (same pump is used in a well and in a fuel station)

Solution:

a. Does not represent reusability because the paper is destroyed before new paper is made. Hence, the old paper loses its identity and cannot be considered the same as the new paper. Consumption is not reusability.

b. Represents reusability because a pump can be used for suction of water as well as petrol. Here, it is not the same pump, but the mechanism (method) is being reused.

Just a Minute…

As a member of a team that is developing the billing system software for Diaz Telecommunications Inc., you have been assigned the task of creating a software module that accepts and displays customer details. Identify the class that you will create and the methods of the class.

Solution: As per the problem statement, the class required is:

Customer

As per the problem statement, the class should have the following methods:

Method to accept customer details

Method to display customer details on the screen

Solutions: Guided Practice 1.P.1 class Ticket { public: void booking() { cout<<"Accepting passenger’s details for booking"; } void print() {

Page 11: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 11

cout<<"Printing the confirmed list of passengers"; } void status() { cout<<"Checking whether the passenger’s name is in the confirmed or

the waiting list"; } };

Page 12: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

12 Object-Oriented Programming ©NIIT

Lesson Two

Experiences You should stress upon the conventions and rules for naming variables.

When explaining the NULL terminator in an array, stress that NULL is a single character represented in C++ programs as \0. Students make the common mistake of assuming that the NULL character must be present at the end of arrays of all data types. Stress that this is true only for strings.

The character NULL is a string terminator and should not be referred to as NULL. The macro NULL is used to initialize and compare pointers and may or may not be defined as zero by different implementations of C++ compilers. The character with the American Standard Code for Information Interchange (ASCII) value of zero is called the NULL character. This character is represented in a C++ program as \0. The macro NULL can be used in a C++ program but the word NULL cannot. The NULL character cannot be displayed on the screen.

Briefly explain the process of preprocessing, compiling, and linking. The diagram labeled, "Steps in the Execution of a C++ Program", given in the lesson may be used.

You should stress upon the fact that a class declaration does not reserve memory at the time of declaration. Memory is allocated when an instance of the class is created. All the objects share the same copy of the member functions, but maintain a separate copy of the member variables. The diagram labeled, "Class and Objects of the Class", given in the lesson may be used.

Examples and Analogies The concept of accessing individual elements of an array with a variable subscript may be introduced to the students. Thus,

float arr[4] = { 1.1, 2.2, 3.3, 4.4 }; cout << arr[1] << endl; // Displays 2.2 int i = 1; cout << arr[i] << endl; // Also displays 2.2 i = i + 1; cout << i << endl; // Displays 2 cout << arr[i] << endl; // Now displays 3.3 i = 0; while (i <= 3) // Traverse the array { cout << arr[i] << " "; // Displays 1.1 2.2 3.3 4.4

i++; }

Students get confused between the value in the subscript variable i and the array variable arr. The statement cout << arr << endl; will display a hexadecimal address corresponding to the starting byte of the array arr. If arr had been a character array with a terminating NULL character, then the cout statement would have displayed all the characters in the array up to NULL i.e., not including the NULL character.

Page 13: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 13

FAQ Q.1. How is the statement, cout << arr[3];, resolved by the compiler?

A.1. The compiler resolves the name arr into the address of the array. The statement arr[3] is resolved by the compiler to imply *(arr + 3).

Q.2. How many objects can a class have?

A.2. Any number. Depends on the amount of memory the computer has.

Q.3. Can there be two classes with the same name?

A.3. Yes provided the classes exist in a separate scope or namespace.

Q.4. Can there be a class within a class?

A.4. Yes. But even public members of the class are not accessible outside the container class.

Q.5. Can there be a function within a function ?

A.5. No, a function cannot be defined within another function.

Q.6. Can you create an object of a class within itself?

A.6. If an object of the same class is created in the constructor or the destructor of the class, it will typically result in abnormal program behavior. The object can be created within any other member function of the class.

Additional Inputs The student can observe all the intermediate files created during the compilation process by typing the following command to compile a C++ program (called myprog.cc in this example).

gpp myprog.cc -o myprog

The following chart shows the intermediate files and steps during compilation.

myprog.cc

myprog.ii

myprog.s

myprog.o

a.out

Preprocess

Compile

Assemble

Link

Page 14: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

14 Object-Oriented Programming ©NIIT

Encourage the students to open all the intermediate files in an editor. If students show interest in learning assembly language, ask them to refer to the book titled, 'Assembly Language Programming for the IBM PC' by Peter Norton and John Socha. The book assumes that the reader has very little knowledge of programming and explains the intricacies of Assembly language in a simple yet lucid manner.

Solutions: Guided Practice 2.P.1

#include <iostream> class Dealer { char firstName[25]; char lastName[25]; char city[25]; char phoneNo[11]; public: void display() { cout << "First Name: "; cout << firstName <<" "; cout <<"Last name: "; cout << lastName << endl; cout << "City: "; cout << city<<" "; cout << "Phone number: "; cout << phoneNo << endl; } void get() { cout << "First name: "; cin >> firstName; cout << endl << "Last Name: "; cin >> lastName; cout << endl << "City: "; cin >> city; cout << endl << "Residence phone number: "; cin >> phoneNo; } }; int main() { Dealer d1; d1.get(); d1.display(); return 0; }

Solution to the Unguided Practice 1. #include<iostream> class Employee

{ char firstName[25]; char lastName[25]; char dateOfBirth[11]; char dateOfJoining[11];

Page 15: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 15

char city[25]; char phoneNo[11]; public: void accept() { cout<<"First name: "; cin>>firstName; cout<<endl<<"Last Name: "; cin>>lastName; cout<<endl<<"Date of Birth: "; cin>>dateOfBirth; cout<<endl<<"Date of Joining: "; cin>>dateOfJoining; cout<<endl<<"City: "; cin>>city; cout<<endl<<"Residence phone number: "; cin>>phoneNo; } void display() { cout<<endl<<"First name: "; cout<<firstName<<endl; cout<<"Last Name: "; cout<<lastName<<endl; cout<<"Date of Birth: "; cout<<dateOfBirth<<endl; cout<<"Date of Joining: "; cout<<dateOfJoining<<endl; cout<<"City: "; cout<<city<<endl; cout<<"Residence phone number: "; cout<<phoneNo<<endl; } }; int main() { Employee e1; e1.accept(); e1.display(); return 0; } 2. #include <iostream> class flightdetails { char flightnum[10]; char dest[20]; char date[8]; public: void f_accept() { cout<<"Enter the flight number:"; cin>>flightnum; cout<<"Enter the destination:"; cin>>dest; cout<<"Enter the date:"; cin>>date; } void f_display() {

Page 16: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

16 Object-Oriented Programming ©NIIT

cout<<"Flight Number:"<<flightnum<<endl; cout<<"Destination:"<<dest<<endl; cout<<"Date:"<<date<<endl; } }; class passengerdetails { char fname[15]; char lname[20]; int age; char sex; public: void p_accept() { cout<<"Enter your first name:"; cin>>fname; cout<<"Enter your last name:"; cin>>lname; cout<<"Enter your age:"; cin>>age; cout<<"Enter your sex(m/f):"<<endl; cin>>sex; } void p_display() { cout<<"First name:"<<fname<<endl; cout<<"Last name:"<<lname<<endl; cout<<"Age:"<<age<<endl; cout<<"Sex:"<<sex<<endl; } }; void main() { flightdetails F1; F1.f_accept(); passengerdetails P1; P1.p_accept(); F1.f_display(); P1.p_display(); } 3. Output: A B 60 The compilation also generates a warning message because the value

60.00 is treated as double and conversion of double to integer datatype results in a warning message.

4. Output: <accepted value> is the age of customer1 <accepted value> is the age of customer2

Solution to the Additional Exercises 1. #include<iostream> class interchange { private:

Page 17: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 17

int var1; int var2; int temp; public: void swap() { var1=5; var2=10; temp=var1; var1=var2; var2=temp; } void display() { cout<<"The new value of variable1 is:"<<var1<<endl; cout<<"The new value of variable2 is:"<<var2<<endl; } }; void main() { interchange I1; I1.swap(); I1.display(); }

Lesson Three

Experiences The concept of abstraction and encapsulation should be introduced with the help of examples from daily life. Mention that encapsulation is also called data hiding. Abstraction and encapsulation complement each other. While going through the examples, mention that the access specifiers can be written in any order in the class. Also, each access specifier may be mentioned any number of times within the class definition.

Tell students that static variables are used in situations where it is required to have one or more variables that are common for all objects. As opposed to member variables, static variables are initialized to zero, when the first object of the class is created.

Examples and Analogies The table about access specifiers in the Student Guide may be used to explain the visibility of class members to objects of the same/other class.

FAQ Q.1. What are static member data and static member functions?

A.1. Static member data and functions belong to the class. You do not need to create an instance of the class to access these members because they come into existence before creating the instance of the class. Static variable retains its value even after the function to which it belongs has been executed. Static functions can only access static variables and not non-static variables

Q.2. What is the general rule to follow for encapsulation and abstraction?

Page 18: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

18 Object-Oriented Programming ©NIIT

A.2. Encapsulate data when you want to hide them. Abstract using a function to access the data.

Q.3. Can I initialize a static member data in the default constructor?

A.3. No, the static member variable should be initialized explicitly even before an object for the class is created.

Additional Inputs You can also tell students about the copy constructor. The copy constructor is required when a new object is to be created from an existing object. Essentially, this situation would arise when you want to create a replica of the object for later references. Also, when the object is passed to a function by value, you would require a copy constructor to initialize the object.

The following code snippet implements the copy constructor:

#include <iostream> class MyInt { int num1; public: MyInt() { num1=0; } MyInt(MyInt *ptr) { num1=ptr->num1; } void disp() { cout<< “Value of Num1 is ->”<<num1; } void accept() { cout<< “\nEnter any numeric value\t”; cin>>num1; } }; void main() { MyInt int1,int2; cout<< “\nThe objects initialization values are\n”; cout<< “Int1 ->”<<int1.disp(); cout<< “Int2 ->”<<int2.disp(); int1.accept(); //Initializing int2 with int1 int2=int1; //Possible because of the copy constructor cout<< “\nValues after assigning are\n”; cout<< “Int1 ->”<<int1.disp(); cout<< “Int2 ->”<<int2.disp(); }

Remember, if the copy constructor is not defined, you would require overloading the assignment operator, which you will learn in the next session.

Page 19: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 19

Just a Minute…

You have defined a Customer class as part of developing the billing system software for Diaz Telecommunications, Inc. The class, which you’ve defined, is as follows:

class Customer { private:

char mobileNo[11]; char name[25]; char dateOfBirth[11]; void print() { //code to print the customer details } public: char billingAddress[51]; char city[25]; char phoneNo[11]; float amountOutstanding; void get() { //code to accept the customer details } };

The Customer class definition shown above is incorrect. Identify the errors in the customer class and write a correct definition for it.

Solution: #include<iostream> class Customer { private: char mobileNo[11]; char name[25]; char dateOfBirth[11]; char billingAddress[51]; char city[25]; char phoneNo[11]; float amountOutstanding; public: void get() { //code to accept the customer details } void print() { //code to print the customer details }

};

Solutions: Guided Practice 3.P.1 class Dealer

Page 20: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

20 Object-Oriented Programming ©NIIT

{ private: char mobileNo[11]; char dealerName[25]; char dealerAddress[51]; char dealerCity[25]; char phoneNo[11]; public: static int CompanyID; static void showID() { cout<<"The company ID is"<<CompanyID; }

void get() { //code to accept the dealer details }

void print() { //code to print the dealer details cout<<"The dealer name is"<<dealerName; } }; int Dealer::CompanyID=6519;

Lesson Four

Experiences In the previous lessons, students have already used the assignment operator. They might also be aware of the arithmetic and comparison operators. If the class is composed of students having a knowledge of these operators, you can begin this session with a quiz about operators. Students would have learned programming constructs and loops in PLT. Therefore, stress can be given on writing the syntax of the constructs and loops. More time should be spend on explaining sorting a one-dimensional array.

Examples and Analogies The diagrammatic representation of sorting an array should be used in the class to explain the program.

FAQ Q.1. What will be the output of the following statement?

for(int i = 0; i < 10 ; i++);

A.1. The variable i will be initialized to 0, then i will be incremented till its value is less then 10. At the end of the loop i will have a value of 10.

Q.2. When do you use a for loop, a while loop, and a do…while loop?

A.2. Use a for loop if you know the number of iterations previously. Use the do…while loop when you want the iteration to occur at least once. A while loop is used when the condition has to be first tested.

Page 21: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 21

Additional Inputs Students frequently misunderstand the execution of the for construct. It must be stressed that the initialization expression in the construct is executed only once. It is possible to have a for construct as given below, provided the statements within the loop contain a break statement.

for(;;) { //statements; }

Just a Minute…

Write a construct that assigns grades to students based on their marks. Students who have scored marks between 75 and 100 are to be given grade ‘A’, those who have scored between 50 and 74 are to be given grade ‘B’, and the rest of them should be given grade ‘C’.

Solution: if(marks >= 75 && marks <= 100)

grade = ‘A’;

else if (marks >= 50 && marks < 75)

grade = ‘B’;

else

grade = ‘C’;

Just a Minute…

Write a function to display the sum of all numbers between 1 and 100.

void sum() {

int num = 1, sum = 0; while(num <= 100) {

sum = sum + num; num = num + 1;

}

cout << sum;

}

Solutions: Guided Practice 4.P.1 #include <iostream> class CalSalary { float amounts[10]; public: void sortData() {

Page 22: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

22 Object-Oriented Programming ©NIIT

int counter=0; amounts[0]=200.5; amounts[1]=323; amounts[2]=0; amounts[3]=100.7; amounts[4]=314; amounts[5]=523; amounts[6]=256; amounts[7]=10.90; amounts[8]=553.90; amounts[9]=0; /* Traverse The Array */ while(counter < 9) { float temp;

/* Compare The Value Of Current Element With The Next */ if(amounts[counter] < amounts[counter + 1]) { /* Swap The Values */ temp = amounts[counter]; amounts[counter] = amounts[counter + 1]; amounts[counter + 1] = temp; counter = 0; continue; } counter++; } } void display() { for(int ctr=0; amounts[ctr]!=’\0’;ctr++) cout<< “ ”<<amounts[ctr]; } }; int main() {

CalSalary L1; L1.sortData(); L1.display();

}

Solution to the Unguided Practice 1. #include <iostream> class Employee {

int salary[10]; public:

void accept_details() {

int counter=0; //Accept value in array

for(;counter<9;counter++) { cout<< “Enter the Salary\n”; cin>>salary[counter]; } } void sort()

Page 23: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 23

{ /* Traverse the array */

while(counter < 9) { int temp;

// Compare The Value Of Current Element With The Next if(salary[counter] < salary[counter + 1])

{ /* Swap The Values */ temp = salary[counter]; salary [counter] = salary [counter + 1]; salary [counter + 1] = temp; counter = 0; continue; } counter++; }

}

void display_asc() {

/* Display All The Array Elements */ for(int counter = 0;counter < 10; ++counter) { if(salary[counter] != 0) { cout << "Element " << salary << ": "; cout << salary [counter] << endl; } } } void display_desc()

{ /* Display All The Array Elements */ for(int counter = 9;counter >= 0; ++counter) { if(salary [counter] != 0) { cout << "Element " << counter << ": "; cout << salary [counter] << endl; } }

} void display_greater() { for(int ctr=0;salary[ctr]!=’\0’;ctr++) if(salary[ctr])>1000) cout<<salary[ctr]; } void display_max() { int max=0; for(int ctr=0;salary[ctr]!=’\0’;ctr++) if(max<salary[ctr]) max=salary[ctr]; cout<< “Maximum Salary is \t”<<max; } void display_min() { int min=0; for(int ctr=0;salary[ctr]!=’\0’;ctr++)

Page 24: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

24 Object-Oriented Programming ©NIIT

if(min>salary[ctr]) min=salary[ctr]; cout<< “Minimum Salary is \t”<<min; }

void avgAmount() { float sum; for(sum = 0.0f, counter = 0; counter < 10; counter++) { sum = sum + salary[counter]; }

cout << endl << "The average amount is : " << sum/10 << endl;

} }; int main() {

Employee empObj; empObj.accept_details(); int choice = 0; empObj.sortData(); while(choice != 6) {

cout << endl << "Menu "; cout << endl << "1. The maximum salary"; cout << endl << "2. The minimum salary"; cout << endl << "3. The average salary"; cout << endl << "4. The number of employees whose salary is greater than 1000"; cout << endl << "5. The salary in ascending and descending orders"; cout << endl << "6. Exit" << endl << endl; cout << "Enter choice "; cin >> choice; switch(choice)

{ case 1: empObj.display_max(); break; case 2: empObj.display_min(); break; case 3:

empObj.avgAmount(); break; case 4: empObj.display_greater(); break; case 5:

cout << endl << "Descending Order " << endl; empObj.display_asc(); cout << "Ascending Order " << endl; empObj.display_desc();

break; case 6: continue;

default: cout << endl << "Please enter 1-6 only !" << endl;

}

Page 25: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 25

} return 0; }

2. #include<iostream> int main() { int month; cout<<"Tell me a month number."; cout<<"I will tell you the number of days in that month."; cin>>month; switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: cout<<"Month has 31 days"; break; case 4: case 6: case 9: case 11: cout<<"Month has 30 days"; break; case 2:

cout<<"Month has either 28 or 29(if leap year) days"<<endl;

break; default: cout<<"There are only 12 months silly"<<endl; } }

3. #include<iostream>

class CountsItself { static int objectCount; int localCount; public: void setCount() { localCount=++objectCount; } void displayCount() { cout<<"Total number of objects :"<<localCount; } }; int CountsItself::objectCount; int main() { CountsItself count1, count2, count3; count1.setCount(); count2.setCount(); count3.setCount(); count3.displayCount();

Page 26: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

26 Object-Oriented Programming ©NIIT

}

Solution to the Additional Exercise 1. output: 3 2.

#include<iostream> int var1=10; int var2=20; class test { public: void disp() { cout<<"var1="<<var1; cout<<"var2="<<var2; } }; class sample { public: void display() { cout<<"var1="<<var1; cout<<"var2="<<var2; } }; int main() { sample S1; S1.display(); }

3. #include<iostream> class values { public: int var1; int var2; int var3; void assign() { var1=5; var2=10; var3=15; } void display() { cout<<"The value of variable1 is:"<<var1<<endl; cout<<"The value of variable2 is:"<<var2<<endl; cout<<"The value of variable3 is:"<<var3<<endl; } }; void main() { values V1; V1.assign();

Page 27: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 27

V1.var2=20; V1.display(); }

Page 28: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

28 Object-Oriented Programming ©NIIT

Lesson Five

Experiences Remember that students have already initialized the member variables in the member-functions of the class. Therefore, point out the advantage of the variables getting initialized in the constructors. Mention that although member functions can be defined inside the class, the practice is to define functions outside the class using the scope resolution operator.

The core strength of C++ lies in its ability to perform pointer manipulation. This is what makes C++ different from Java. The students must be strongly advised to read section “Call by Reference Using Pointers” of the Student Guide. You may recommend the student to read the book titled, ‘Pointers in C++’, by Yashavant Kanetkar. Although this book is written for the C programming language, it explains the use of pointers very clearly and in great detail.

A lot of students shy away from C and C++ programming if pointers are not dealt with properly in class.

FAQ Q.1. Can a class have more than one constructor?

A.1. Yes, a class can have more than one constructor. A class can have one default constructor and many argument constructors.

Additional Inputs Tell students that since the constructor is invoked automatically it cannot have a return type. Also, the parameter constructor can be initialized with default values, if the user does not supply one.

For example: Consider the following class:

class Number { public: add(int val1=10,int val2=0) { tot=val1+val2; } }; void main() { Number nObj(3); }

The above class will invoke the constructor and initialize va1 with 3 and val2 with 0.

Just a Minute…

Given is a code snippet for the main() function of a program. How would you ensure that the following tasks are accomplished when the program is executed:

1. The member variables are initialized with zero

Page 29: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 29

2. On exit or termination of the program the following message is displayed : “Bye Folks!!! Have a Nice Time”

#include <iostream> int main() { Number num1; num1.disp(); }

Hint: The Number class has only one member variable myNum.

Solution: class Number { int myNum; public: Number() { myNum=0; } ~Number() { cout<< “Bye Folks!!! Have a Nice Time”; } void disp() { cout<< “Value contained in Num1 is ”<<myNum; };

Solutions: Guided Practice 5.P.1 Solution: 10 100 5.P.2 Solution: 10 100

Lesson Six

Experiences The concept of polymorphism should be explained by taking examples from real life. After explaining the examples in the student guide, ask students to give some real life examples of polymorphism.

Begin the class by showing students, a class declaration having only one member variable. Create three objects of the class and perform addition of two objects using the '+' operator. Assign the result to the

Page 30: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

30 Object-Oriented Programming ©NIIT

third object (obj1=obj2+obj3). Ask about the output from the students. Mention that such type of addition can be performed using operator overloading.

Examples and Analogies While explaining call by value type of functions, you can also show a program in which the main() function calls another function, which takes a single integer parameter and modifies it. This can be repeated for other types of function calls.

Analogies for function overloading could be: A little boy cries when he sees a ferocious animal but smiles when he sees his mother. In both cases, the object (the little boy) is the same, but the response (comparable to a function) depends on the input parameter (the ferocious animal or his mother).

An analogy that can be given in class is the base class - vertebrates and subclasses as mammals and birds.

The following is an analogy to explain the overloading of the + operator:

Consider the statement, bigRect = smallRect1 + smallRect2;! Until now you been using the operators = and + only with numbers. However the two operators = and +, can be defined with an additional function of recognizing objects of the class Rectangle. This is known as operator overloading.

As an additional exercise, the student may be asked to create a Word class with overloaded operators.

FAQ Q.1. How many bytes does a pointer variable occupy?

A.1. This is implementation-dependent and can vary from two to eight bytes.

Q.2. Why are pointers needed ?

A.2. The various advantages of using pointers are:

• Pointers allow direct access to individual bytes in the memory. Thus, data in memory is accessed faster than through ordinary variables. This speeds up the execution of programs.

• Pointers allow direct access to output devices, like the monitor. This speeds up programs that are graphics intensive.

• Pointers allow the program to allocate memory dynamically, only when required, with the help of the new operator. They also allow the program to free the memory when it is no longer required. This is done with the help of the delete operator. You will read about these operators later in this section.

Q.3. Where are the default behaviors of the +, -, *, and / operators defined?

A.3. They are defined in the C++ library.

Q.4. Does the use of operator overloading increase the efficiency of the program? In other words, is it faster than a function call?

A.4. No, it does not increase the efficiency of the program since, to define the overloaded operator, you would need to define a function.

Page 31: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 31

Additional Inputs In order to store the signature of a function, the C++ compiler performs a process known as name mangling.

If you pass an object to a function as a value, then the constructor of the object would be executed as soon as the function is invoked. This would mean that there are two objects in the memory - one in the calling function and one in the called function. However, if the object is passed as an alias or as a pointer, then no new object is created and, therefore, the constructor does not get invoked.

Operator Overloading In this concept, use the example explained below to make students understand operator overloading implementation.

Here, faculty needs to show the code provided in “operator_overloading.cc “ datafile under “Data Files\OOPS\Session 6(Part-2)“ folder in the TIRM CD. In this example the functionality is implemented using functions, the concept students are comfortable with. This example will clarify the working of operator overloading. After, explaining this, faculty should show the actual implementation-using operator overloading code. Please tell students that this example is used for explanation purposes but in practice they need to use the operator overloading implementation only.

#include<iostream>

class Number { private: int number; public: Number(int = 0); //Constructor /* Operations */ Number plus(int = 0); Number plus(Number); void display(); //Function }; Number :: Number(int num) { number = num; } Number Number :: plus(int num) { Number temp; temp.number = number + num; return temp; } Number Number :: plus(Number objnum) { Number temp; temp.number = number + objnum.number; return temp; } void Number :: display() { cout << number << endl; } int main() { Number num1(100); Number num2(200); Number num3 = num1;

Page 32: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

32 Object-Oriented Programming ©NIIT

Number tot; tot = num1.plus(50); tot.display(); //Displays 150 tot = num1.plus(num2); tot.display(); //Displays 300 num3.display(); //Displays 100 return 0; }

After explaining this example, Faculty can replace plus function, as plus operator (code given in the SG).

You can ask the students to overload the operators, !, >=, and <= in addition to solving the problem of the student guide.

You can give the following program to the students for extra practice.

Consider the following program:

#include<iostream> class distance { int length; public: distance(int); void operator >(distance); };

distance::distance(int a) { length=a; } int main() { distance d1(20); distance d2(30); d1>d2; return 0; }

The function definition for the 'operator >()' function is missing. Write the function definition to overload the ‘>’ operator to compare two objects d1 and d2 of the distance class. The operator function should display a meaningful message.

Solution: #include<iostream> class distance { int length; public: distance(int); void operator >(distance); }; distance::distance(int a) { length=a; } void distance::operator >(distance d) {

Page 33: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 33

if (length>d.length) { cout<<length<<" is greater than "<<d.length; } else { cout<<length<<" is not greater than "<<d.length; } } int main() { distance d1(20); distance d2(30); d1>d2; return 0; }

Just a Minute…

Modify the existing employee class such that when the following statements are given in the main() function, the program successfully compares the basic salary of the employees and displays the given message.

#include <iostream> void main() { Employee eObj1, eObj2; eObj1.getdata(); //Accepts data eObj2.getdata(); if(eObj1<eObj2) cout<< “Employee 1 draws less salary than Employee 2”; else cout<< “Employee 2 draws less salary than Employee 1”; } Solution: Employee Employee:: operator < (Employee &emp) { if (basic_salary < emp.getSalary()) return 1; else return 0; } //Since you cannot access private member variables of the class you need //to also code for the getter of the variable int getSalary() { return basic_salary;

}

Solutions: Guided Practice 6.P.1 Solution: 1,3, and 4

Page 34: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

34 Object-Oriented Programming ©NIIT

6.P.2 Solution: void display()- To display all employee records void display(char ecode[])- To display employee details based on code void display(char dept[])- To display employee details based on department name 6.P.3 Solution: #include<iostream> class distance { int length; public: distance(int); void operator =(distance); }; distance::distance(int a) { length=a; } void distance::operator =(distance d) { if (length=d.length) { cout<<length<<" is equal to "<<d.length; } else { cout<<length<<" is not equal to "<<d.length; } } int main() { distance d1(20); distance d2(20); d1=d2; return 0; } 6.P.4 Solution : Employee Employee:: operator +=(int val) { basic += val

}

Solution to the Unguided Practice 1 #include<stdio.h>

#include<iostream>

Page 35: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 35

class Time { //Declare hour, minute, and second int hour; int minute; int second; public: //Default constructor Time() { hour=0; minute=0; second=0; } //Constructor to set hour, minute, and second Time(int hr, int min=0, int sec=0) { hour=hr; minute=min; second=sec; }

void setTime(int hr,int min,int sec); void setTime(int min); //second void setTime(int min,int sec); void display() { cout<<hour<<":"<<minute<<":"<<second<<endl; } }; void Time::setTime(int hr, int min, int sec) { hour=hr; minute=min; second=sec; } void Time::setTime(int min) { minute=min; } void Time::setTime(int min, int sec) { minute=min; second=sec; } int main() { //Time object Time time; //Setting hour, minute, and second time.setTime(12,30,50); //Displaying time in the hh:mm:ss format time.display(); //Setting the minute to 35 minutes past 12:00 time.setTime(35); time.display();

Page 36: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

36 Object-Oriented Programming ©NIIT

//Setting the minute and second time.setTime(42, 31); time.display(); }//End of main()

2. #include <iostream> class DayCount { int month; int year; int days; public: //constructor to initialize month and year to 0 DayCount() { month=0; year=0; } //returns 1 if year is a leap year, else returns 0 int leap() { if (year%4 ==0 || year%400!=0) return 1; return 0; } //sets the month and year void setDate(int mth, int yr) { year=yr; month=mth; } // sets the month, overloaded function void setDate(int mth) { month=mth; } //returns the name of the month char *monthName() { switch(month) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December”; } } //sets the number of days in a month void setDays() { switch(month) { case 1:case 3: case 5:case 7:case 8:case 10:case 12: days=31; break; case 2: days=28; if (leap())

Page 37: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 37

days=29; break;//assign 29 days if leap year case 4:case 6:case 9:case 11: days=30; break; } } void display() { setDays(); cout<< "The number of days for the month of "<<monthName(); cout << " is "<<days<<endl; } }; int main() { int mm,yy; DayCount dayCount; cout<<”Enter month”<<endl; cin>>mm; cout<<”Enter year”<<endl; cin>>yy; dayCount.setDate(mm,yy); dayCount.display(); }

Solution to the Additional Exercise 1. The number is 4Number is 20The number in main()after calling

showNumber is 4Number inside displayNumber is 30The number in main() after calling displayNumbers is 30

Lesson Seven

Experiences Explain the theoretical concepts of inheritance, composition, utilization, and instantiation. Ask students to give real life examples of inheritance. This way you can generate enthusiasm among students, also, it will help improve student interaction. Stress on the importance of the protected access specifier while implementing inheritance in C++.

Examples and Analogies The table in lesson 7 of the student guide that illustrates the three types of inheritance may be used to explain the members derived from the base class.

FAQ Q.1. What is the access specifier of an inherited member if it is inherited using protected access

specifier?

A.1. When you derive a class from the base class, all public members of the base class are inherited as protected and protected members are inherited as private.

Page 38: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

38 Object-Oriented Programming ©NIIT

Q.2. Is the constructor inherited?

A.2. Constructors are not inherited.

Q.3. Can a constructor be declared private?

A.3. Yes you can. You might do it for high level programming.

Additional Inputs You can read the paper on C++ APIs on the Internet at the following address:

http://www.symbian.com/epoc/papers/cppapi/cppapi.html#cppapi.cppapi-035

This paper gives an overview of C++ inheritance and other C++ related topics.

Just a Minute…

Solution :

The hierarchy is given as follows:

Just a Minute…

Solution :

The relationships are as follows:

1 and 5 Composition relationship

2 and 3 Inheritance relationship

4 No relationship. Tea is not an attribute of a cup.

Just a Minute…

Solution : The utilization relationships are:

Salesperson mans Counter

Page 39: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 39

Counter deals-in Product

Customer buys Product

Customer pays Salesperson

Solution to the Guided Practice 7.P.1 Solution : //Class will be used for inheritance purpose only

class Shape { //Class variables protected: int length; int breadth; int area; public: //The constructor Shape() { length=0; breadth=0; } //Function to set parameters void setParameters()=0; //Function to display parameters void displayParameters()=0; //Function to draw shape, will print a message void draw()=0; void calculateArea()=0; }; class Rectangle: public Shape { void setParameters() { cout<<”Enter length and breadth:”; cin>>length; cin>>breadth; } void displayParameters() { cout<<”Length and breadth are:”<<length<<”:”<<breatdh; } //Function to draw shape, will print a message void draw() { cout<<”Draw a rectangle”; } void calculateArea() { cout<<”Area:”<<length*breadth; } }; class Circle:public Shape

Page 40: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

40 Object-Oriented Programming ©NIIT

{ int radius; void setParameters() { cout<<”Enter radius”; cin>>radius; } void displayParameters() { cout <<”Radius is :”<<radius; } //Function to draw shape, will print a message void draw() { cout<<”Draw Circle”; } void calculateArea() { cout<<”Area is:<<3.14*radius/2; } }; int main() { //use to test the implementation //Ask user what he wants to draw and draw accordingly Shape *shape; cout <<”Specify what you want to draw:” cout <<”R for rectangle”<<endl; cout <<”C for circle”<<endl; char choice; cin>>choice; switch(choice) { case ‘R’: case ‘r’: shape= new Rectangle(); break; case ‘C’: case ‘c’: shape=new Circle(); } shape.setParameters(); shape.displayParameters(); shape.calculateArea(); shape.draw();

}

Lesson Eight

Experiences You can give the example of a mammal class exhibiting dynamic polymorphism for the behavior movement. You can explain this using examples of different mammals - a bat exhibits movement by flapping its wings, a whale exhibits movement by its blubber, and a human being exhibits movement by using limbs.

Page 41: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 41

Give a brief recap of invoking member functions by different objects of the same class. Mention that the process of associating an object to the function is called binding. Tell students that binding is necessary because there is only one copy of a member function for the different objects of the same class. Then, explain the following program, which demonstrates the concept of late binding.

Examples and Analogies The following program demonstrates the concept of late binding:

#include <iostream> class base { public: virtual void func() { cout << "BASE" << endl; } }; class derived : public base { public: void func() { cout << "DERIVED" << endl; } }; int main() { base *ptr; int var; cout << "Enter 1 or 2 : "; cin >> var; if (var == 1) { ptr = new base; } else { ptr = new derived; } ptr -> func(); // At compile time, the outcome of this statement // is undeterminable - an example of late binding return 0; }

Here is an analogy for a pure virtual function. Consider the base class, Animalia. All animals have certain common features, for example, they all move. Therefore, move() is a function of the base class Animalia. But they move in different ways. A bird flies, a reptile crawls, and a fish swims. Hence, the move() function cannot be defined in the base class. It is, therefore, a suitable candidate for a pure virtual function. The class Animalia has several classes derived from it. They are Fish, Bird, Man, Tortoise and so on.

The hierarchy may thus be coded as:

#include <iostream> class Animalia { public: void breath() // ordinary member function {

Page 42: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

42 Object-Oriented Programming ©NIIT

cout << "Oxygen" << endl; } virtual void move() = 0; // pure virtual function }; class Fish : public Animalia { public: void move() { cout << "Swim" << endl; } }; int main() { Animalia * ptr; // permitted Animalia obj; // ERROR: Abstract class cannot be instantiated Fish gold; gold.breath(); // displays Oxygen gold.move(); // displays Swim return 0; }

Additional Inputs As an additional exercise, you can ask the students to create the Word class that provides the functionality of copying and appending the values.

Solutions: Unguided Practice 1. putData of book: void putData() { cout<< “Title:”<<title<<endl; cout<< “Price:”<<price<<endl; cout<< “No of Pages:”<<pageCount<<endl; } the tape class: class tape: public publication { int playingTime; public: void getData(char *name, float price, int time) { getData(name, price); playTime=time; } void putData() { cout<< “Title:”<<title<<endl; cout<< “Price:”<<price<<endl; cout<< “Playing time:”<<playingTime<<endl; } };

2. class Furniture { protected: int numberOfLegs; int height;

Page 43: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 43

int width; int length; public: void display(); }; class Chair:public Furniture { public: void display() { cout<< “Chair”; } }; class Table:public Furniture { public : void display() { cout<< “Table”; } }; void display() { cout<< “C for chair”; cout << “T for table”; cout<< “Q to quit”; } int main() { Furniture *furniture; char choice; display(); cin>>choice; while(choice!=’Q’) { switch(choice) { case ‘T’: furniture=new Table; break; case ‘C’: furniture=new Chair; break;

default: cout<< “Invalid option. Enter C, T, or Q”<<endl;

} furniture.display(); display(); cin>>choice; } }//end of main

Solution to the Additional Exercise 1. class RandomNumbers

{ int seed; float count;

Page 44: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

44 Object-Oriented Programming ©NIIT

public: //intialize the seed variable, by default to zero RandomNumbers(int seed=0) { this.seed=seed; //this will avoid calculating again and again count=180.0/3.14; } //calculate a single random number float random () { return seed/count; } //calculate and display many random numbers float displayRandom(int counter) { for(int i=1; i<counter; i++){ float random=seed/(count*I); cout<<”Random number is: “<<random<<endl; } } }; void displayMenu() { cout<<”Want random numbers?(Y/N)”; } int main() { int choice; int number; displayMenu(); RandomNumbers randomNumber;//Moved out of loop //To stop repeated instantiation while(choice!=’n’||choice!=’N’) { cout << “How many random numbers do you want?”; cin>>number; if(number==1) { int random=randomNumber.random(); Cout<< “Random number is :”<<random; } else { randomNumber.displayRandom(); } displayMenu(); cin>>choice; } }

2. class Book {

protected:

Page 45: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 45

char *bookName; char *bookAuthor; char *publisher; char *isdnNumber; int numberOfPages; float price; public : Book(char *name,char *author,char *publisher, char *number,

int pages, float rate) { bookName=name; bookAuthor=author; this.publisher=publisher; isdnNumber=number; numberOfPages=pages; price=rate; } void displayDetails() { cout<<”\tTitle\tAuthor\tpublisher\tISDN Number\tPages\tPrice\n”; cout<<bookName<<”\t”<<bookAuthor<<\t<<publisher <<”\t”<<isdnNumber<<”\t”<<numberOfPages <<”\t”<<price<<endl; } void setPrice(int price) { this.price=price;); } }; class TextBook { char *subject; public: TextBook(char *name, char *author,char *publisher, char *number, int pages,float rate, char *subject):Book(name,author,publisher, number,pages,rate){ this.subject=subject; } void displayDetails() { cout<<”\tTitle\tAuthor\tsubject\tpublisher\tISDN Number\tPages\tPrice\n”; cout<<bookName<<”\t”<<bookAuthor<<\t<<subject<<”\t”publisher <<”\t”<<isdnNumber<<”\t”<<numberOfPages <<”\t”<<price<<endl; }

Page 46: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

46 Object-Oriented Programming ©NIIT

}; class ReferenceBook { public: ReferenceBook(char *name, char *author,char *publisher, char *number, int pages,float rate):Book(name,author,publisher, number,pages,rate) { } void setPrice(int price) { this.price=price;); } }; class StoryBook { char *type; public: StoryBook(char *name, char *author, char *publisher, char *number, int pages,float rate, char * type):Book(name,author,publisher, number,pages,rate){ this.type=type; } void displayDetails() { cout<<”\tTitle\tAuthor\tpublisher\tISDN Number\t Pages\tPrice\tType\n”;

cout<<bookName<<”\t”<<bookAuthor<<\t<<publisher <<”\t”<<isdnNumber<<”\t”<<numberOfPages

<<”\t”<<price<<”\t”<<type<<endl; } };

3. A created B created with value: 20

Lesson Nine

Experiences Mention the fact that many natural and man-made phenomena exhibit multiple inheritance. Ask them to give real life examples of multiple inheritance. Then, tell them that because object-oriented systems have to model real life, there is a mechanism for implementing multiple inheritance in C++.

Examples and Analogies The following program demonstrates the concept of late binding:

#include <iostream> class device { protected: int dev_no; char dev_name[15];

Page 47: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 47

public: void getdata() { cout<<"Enter device number :: "; cin>>dev_no; cout<<"Enter device name :: "; cin>>dev_name; } void showdata() { cout<<dev_no; cout<<dev_name; } }; class input: virtual public device { protected: int speed_reading; public: void showdata() { device :: showdata(); cout<<speed_reading; } void getdata() { device ::getdata(); cout<< "Enter speed_reading :: "; cin>>speed_reading; } }; class output: virtual public device { protected: int speed_writing; public: void getdata() { device :: getdata(); cout<<"Enter speed of writing :: "; cin>>speed_writing; } void showdata() { device :: showdata(); cout<<speed_writing; } }; class input_output_device: public input, public output { private: int type; public: void showdata() { cout<<"\n\nInput Device"; input :: showdata(); cout<<"\n\nOutput Device"; output :: showdata(); cout<< type; }

Page 48: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

48 Object-Oriented Programming ©NIIT

void getdata() { cout<<"\nEnter the data regarding Input Device\n"; input :: getdata(); cout<<"\nEnter the data regarding Output Device\n"; output :: getdata(); cout<<"Enter type :: "; cin>>type; } }; int main() { char ch; int ret =0; input_output_device iod; do { cout<<"\n1. Enter Device"; cout<<"\n2. Show Device"; cout<<"\n3. Exit"; cout<<"\n\nEnter the choice :: "; cin>>ch; switch(ch) { case '1': iod.getdata(); ret=1; break; case '2': iod.showdata(); ret=1; break; case '3': ret=0; break; default: ret=1; break; } }while(ret); return 0; }

Additional Inputs You can tell the students about the hybrid inheritance implementation. For example:

Page 49: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 49

After completing the session and allocating iSAS topics to the students, you can use the OOPS_Recap slides given in the slides->OOPs folder to revise the concepts learnt so far. The questons given in this slide show are also given in the appendix as Recap.

Solution to the Guided Practice 9.P.1 Solution :

#include <iostream.h> class application { protected: char appcode[4]; int storagespace; public: void getapp() { cout<<"enter application code:"; cin>>appcode; cout<<"enter the storage requirement"; cin>>storagespace; } void showapp() { cout<<endl<<"Application code :"<<appcode<<endl; cout<<"Storage space"<<storagespace<<endl; } }; class spellchecker:virtual public application { protected: char lang[5]; public: void getspell() { cout<<"enter the language:"; cin>>lang; } void showspell() { cout<<"Language:"<<lang<<endl; } }; class calculator:virtual public application { protected: int noofoperations; public: void getcal() { cout<<"enter no of operations"; cin>>noofoperations; } void showcal() { cout<<"no of operations"<<noofoperations<<endl; } }; class spreadsheet : public spellchecker,public calculator {

Page 50: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

50 Object-Oriented Programming ©NIIT

private: int noofsheets; public: void getsheet() { getapp(); getspell(); getcal(); cout<<"enter no of sheets"; cin>>noofsheets; } void showsheet() { showapp(); showspell(); showcal(); cout<<"No of Sheets :"<<noofsheets<<endl; } }; int main() { spreadsheet s; s.getsheet(); s.showsheet(); return 0; }

Lesson Ten

Experiences You can start the class by stating the need for files and build the session by describing files and their components. Please - spend some time explaining the stream class hierarchy so that the students are not confused with terms such as inserters and extractors. Discuss the examples given in the book to explain the read/write operations for fundamental data types and user-defined data types.

Examples and Analogies The following problem statement can be given as practice.

1. Write an application to accept two file names from the user and display the number of records and total number of bytes occupied by the files.

2. Write an application that will compare the contents of the two files and print whether they are same or not.

3. Write an application that will reverse the contents of any given text file. For example, if the file contains the following statement:

“Faith is a cure of all worries”

The output should be: “worries all of cure a is Faith”

FAQ

Page 51: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 51

1. Can a single file object open more than one file in a given program?

A.1. Yes, only if the object has closed the previously opened file.

2. Can we modify the contents of a file?

A.2. A file can be modified by following the given steps::

a) Open the file in input/output mode

b) Search the record to be modified

c) Position the put pointer at the beginning of the record that has to be modified

d) Modify the values and re-write the record at the same location

e) Close the file

3. Can the cin operator accept white spaces?

A.3. Yes, the cin.get() accepts white spaces.

Solutions: Guided Practice 10.P.1 Solution : #include <iostream> #include <fstream> #include <string> class NRailways { private: string pnr; string pname; string date_departure; string to; string from; char status; int No_of_Seats; public: void print() { cout<<"\n\n PNR Number :\t"<<pnr; cout<<"\n Passenger Name :\t"<<pname; cout<<"\n Date of Departure :\t"<<date_departure; cout<<"\n Destination To :\t"<<to; cout<<"\n From :\t"<<from; cout<<"\n Status of Booking :\t"<<status; cout<<"\n # of Seats Reserved :\t"<<No_of_Seats; } void get() { cout << "Enter the PNR Number:\t"; cin >> pnr; cout << endl << "Enter Passenger Name:\t"; cin>>pname; cout << endl << "Enter Date of Departure: \t"; cin >> date_departure; cout << endl << "From:\t";

Page 52: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

52 Object-Oriented Programming ©NIIT

cin>>from; cout << endl << "To:\t "; cin>>to; cout << endl << "Enter Status of Booking\t"; cin >> status; cout << endl << "Enter # of Seats Reserved:\t"; cin >> No_of_Seats; } char getstatus() { return status; } }; int main() { int ch; NRailways object; while(1) { cout<< "\n \n Northern Railway System\n"; cout<< "\n 1. Enter Passenger Details \n"; cout << "\n 2. Print Confirmed Booking List \n"; cout << "\n Enter your choice (0-2)\t"; cin>>ch; if(ch==1) { ofstream ofile("booking.dat"); char reply = 'Y'; while(reply == 'Y' || reply == 'y') { cout << "Enter Passenger Details " << endl; object.get(); ofile.write((char *)&object,sizeof(object)); cout << "Do you wish to continue ?[Y/N]"; cin >> reply; } ofile.close(); } if(ch==2) { ifstream ifile("booking.dat"); ifile.read((char *)&object, sizeof(object)); while(ifile) //Read Till The End Of The File { if(object.getstatus()=='C') object.print(); ifile.read((char *)&object, sizeof(object)); } ifile.close(); } if(ch==0) break; } return 0; } 10.P.2 Solution :

Page 53: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 53

#include <iostream> #include <fstream> #include <string> class NRailways { private: char pnr[6]; char pname[30]; char date_departure[9]; char to[40]; char from[40]; char status; int No_of_Seats; public: NRailways() { pnr[0]='\0'; pname[0]='\0'; date_departure[0]='\0'; to[0]='\0'; from[0]='\0'; status=' '; No_of_Seats=0; } void print() { cout<<"\n\n PNR Number :\t"<<pnr; cout<<"\n Passenger Name :\t"<<pname; cout<<"\n Date of Departure :\t"<<date_departure; cout<<"\n Destination To :\t"<<to; cout<<"\n From :\t"<<from; cout<<"\n Status of Booking :\t"<<status; cout<<"\n # of Seats Reserved :\t"<<No_of_Seats; } void get() { cout << "Enter the PNR Number:\t"; cin >> pnr; cout << endl << "Enter Passenger Name:\t"; cin>>pname; cout << endl << "Enter Date of Departure: \t"; cin >> date_departure; cout << endl << "From:\t"; cin>>from; cout << endl << "To:\t "; cin>>to; cout << endl << "Enter Status of Booking\t"; cin >> status; cout << endl << "Enter # of Seats Reserved:\t"; cin >> No_of_Seats; } char getstatus() { return status; } char *getpnr() { return pnr; }

Page 54: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

54 Object-Oriented Programming ©NIIT

void setstatus() { char choice; cout<<"\n\n Do you want to cancel the Booking?\t"; cin>>choice; if(choice=='y' || choice=='Y') status='R'; } }; int main() { int ch; while(1) { cout<< "\n \n Northern Railway System\n"; cout<< "\n 1. Enter Passenger Details\n"; cout<< "\n 2. Query Passenger Details \n"; cout<< "\n 3. Cancel the Booking \n"; cout<< "\n 4. Print Confirmed Booking List\n"; cout << "\n Enter your choice (0-4)\t"; cin>>ch; if(ch==1) { NRailways object; fstream ofile("booking1.dat",ios::app); cout << "Enter Passenger Details " << endl; object.get(); ofile.write((char *)&object,sizeof(object)); ofile.close(); } if(ch==2) { NRailways object; ifstream ifile("booking1.dat"); char pnr[6]; cout<<"\n\n Enter the PNR Number:\t"; cin>>pnr; ifile.seekg(0,ios::beg); ifile.read((char *)&object, sizeof(object)); while(ifile) //Read Till The End Of The File { char temp[6]; strcpy(temp,object.getpnr()); if(strcmp(temp,pnr)==0) { object.print(); break; } ifile.read((char *)&object, sizeof(object)); } ifile.close(); } if(ch==3) { NRailways o; fstream ie("booking1.dat",ios::in|ios::out); char pnr[6]; int pos; cout<<"\n\n Enter the PNR Number:\t"; cin>>pnr;

Page 55: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 55

ie.read((char *)&o, sizeof(o)); while(ie) //Read Till The End Of The File { char temp[6]; pos=ie.tellg(); strcpy(temp,o.getpnr()); if(strcmp(temp,pnr)==0) { o.setstatus(); ie.seekp(pos-sizeof(o),ios::beg); ie.write((char*)&o,sizeof(o)); ie.close(); break; } else ie.read((char *)&o, sizeof(o)); } ie.close(); } if(ch==4) { NRailways object; ifstream ifile("booking1.dat"); ifile.read((char *)&object, sizeof(object)); while(ifile) //Read Till The End Of The File {

if(object.getstatus()=='C'||object.getstatus()=='c')

object.print(); ifile.read((char *)&object, sizeof(object)); } ifile.close(); } if(ch==0) break; } return 0; }

Solution to the Unguided Practice 1. #include <string>

#include <iostream> #include <fstream> class Customer { private: char mobileNo[11]; char name[25]; char dateOfBirth[9]; char billingAddress[51]; char city[25]; char phoneNo[11]; float amountOutstanding; public: Customer() { mobileNo[0]='\0';

Page 56: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

56 Object-Oriented Programming ©NIIT

name[0]='\0'; dateOfBirth[0]='\0'; billingAddress[0]='\0'; city[0]='\0'; phoneNo[0]='\0'; amountOutstanding=0; } void print() { cout << endl << "Mobile phone number: "; cout << mobileNo << endl; cout << "\nName: "; cout << name << endl; cout << "\nDate of Birth: "; cout << dateOfBirth<<endl; cout << "\n\nCustomer's billing address: "; cout << billingAddress<<endl; cout << "\nCity: "; cout << city << endl; cout << "\nResidence phone number: "; cout << phoneNo << endl; cout << "\nAmount due: "; cout << amountOutstanding << endl; } void get() { cout << "Mobile phone number: "; cin >> mobileNo; cin.ignore(); cout << endl << "Name: "; cin.getline(name,25); cout << endl << "Date of Birth: "; cin >> dateOfBirth; cin.ignore(); cout << endl << "Customer's billing address: "; cin.getline(billingAddress,51); cout << endl << "City: "; cin.getline(city,25); cout << endl << "Residence phone number: "; cin >> phoneNo; cout << endl << "Amount due: "; cin >> amountOutstanding; } char *getmbno() { return mobileNo; } }; int main() { int ch; Customer object; while(1) { cout<< "\n \n Diaz Customer Tracking System\n"; cout<< "\n 1. Enter Customer Details\n"; cout << "\n 2. Display all records \n"; cout <<" \n 3. Query \n"; cout << "\n Enter your choice (0-3)\t"; cin>>ch;

Page 57: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 57

if(ch==1) { ofstream ofile("customer.dat"); cout << "Enter customer details " << endl; object.get(); ofile.write((char *)&object,sizeof(object)); ofile.close(); } if(ch==2) { ifstream ifile("customer.dat"); ifile.read((char *)&object, sizeof(object)); while(ifile) //Read Till The End Of The File { object.print(); ifile.read((char *)&object, sizeof(object)); } ifile.close(); } if(ch==3) { Customer c1; ifstream ie("customer.dat"); char mbno[11]; int pos; cout<<"\n\n Enter the Mobile Number:\t"; cin>>mbno; ie.read((char *)&c1, sizeof(c1)); while(ie) //Read Till The End Of The File { char temp[11];

strcpy(temp,c1.getmbno()); if(strcmp(temp,mbno)==0) { c1.print(); break; } else ie.read((char *)&c1, sizeof(c1)); } ie.close(); } if(ch==0) break; } return 0; }

2. #include <iostream>

class device { protected: int dev_no; char dev_name[15]; public: void getdata() { cout<<"Enter device number :: "; cin>>dev_no; cout<<"Enter device name :: "; cin>>dev_name;

Page 58: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

58 Object-Oriented Programming ©NIIT

} void showdata() { cout<<dev_no; cout<<dev_name; } }; class input: virtual public device { protected: int speed_reading; public: void showdata() { device :: showdata(); cout<<speed_reading; } void getdata() { device ::getdata(); cout<< "Enter speed_reading :: "; cin>>speed_reading; } }; class output: virtual public device { protected: int speed_writing; public: void getdata() { device :: getdata(); cout<<"Enter speed of writing :: "; cin>>speed_writing; } void showdata() { device :: showdata(); cout<<speed_writing; } }; class input_output_device: public input, public output { private: int type; public: void showdata() { cout<<"\n\nInput Device"; input :: showdata(); cout<<"\n\nOutput Device"; output :: showdata(); cout<< type; } void getdata() { cout<<"\nEnter the data regarding Input Device\n"; input :: getdata(); cout<<"\nEnter the data regarding Output Device\n"; output :: getdata(); cout<<"Enter type :: ";

Page 59: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 59

cin>>type; } }; int main() { char ch; int ret =0; input_output_device iod; do { cout<<"\n1. Enter Device"; cout<<"\n2. Show Device"; cout<<"\n3. Exit"; cout<<"\n\nEnter the choice :: "; cin>>ch; switch(ch) { case '1': iod.getdata(); ret=1; break; case '2': iod.showdata(); ret=1; break; case '3': ret=0; break; default: ret=1; break; } }while(ret); return 0; }

Solution to the Additional Exercise 1. // A program to count the no of vowels in a file

// and display on screen #include<fstream> int main() { int i=0; char fname[15]; cout<<"Enter the file name :"; cin>>fname; char ch; ifstream ifile(fname); while(ifile) { ifile.get(ch); if(ch >='A' && ch <='Z') //convert all uppercase alphabets to lowercase { ch=ch+32;//so that you can check only lowercase vowels } switch(ch)

Page 60: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

60 Object-Oriented Programming ©NIIT

{ case 'a' :i=i+1; break; case 'e': i=i+1; break; case 'i': i=i+1; break; case 'o' :i=i+1; break; case 'u': i=i+1; break; } } cout<<"The total count of alphabets is: "<<i; }

2. #include<fstream> int main() { char fname[15]; cout<<"Enter the file name :"; cin>>fname; char ch; ifstream ifile(fname); while(ifile) { ifile.get(ch); if(ch>='a' && ch<='z') // In case the file contains any lower case

//alphabets { ch=ch-32; } cout<<ch; }; cout<<endl; } 3. #include<fstream> class fileoperation { char fname[15]; int i; char ch; public: void fileopen(); void vowel(); void chgcase(); }; void fileoperation::fileopen() { cout<<"Enter the file name :"; cin>>fname; ifstream ifile(fname); } void fileoperation::vowel() { i=0; ifstream ifile(fname);

Page 61: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 61

while(ifile) { ifile.get(ch); if(ch >='A' && ch <='Z') //convert all uppercase alphabets to

//lowercase { ch=ch+32;//so that you can check only lowercase vowels } switch(ch) { case 'a' :i=i+1; break; case 'e': i=i+1; break; case 'i': i=i+1; break; case 'o' :i=i+1; break; case 'u': i=i+1; break; } } cout<<"The total count of alphabets is: "<<i; void fileoperation::chgcase() { ifstream ifile(fname); while(ifile) { ifile.get(ch); if(ch>='a' && ch<='z') // In case the file contains any lower case

//alphabets { ch=ch-32; } cout<<ch; }; cout<<endl; } int main() fileoperation f1; { fileoperation f1; f1.fileopen(); f1.vowel(); f1.chgcase(); }

Page 62: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

62 Object-Oriented Programming ©NIIT

SOLUTION: ADDITIONAL EXERCISES

Ans 1. Some attributes of a mobile are:

Color

Size

Make

Weight

Memory

Some functionalities of a mobile are:

Make calls

Receive calls

Ring

Remember data

The different components that should be purchased to build a mobile are:

Keys

Chips

Memory

Cell

Antenna

The cover

Ans 2. In the above example, the attributes and functionalities listed are common for any mobile. But a particular mobile of Diaz Telecommunication will be different from the mobiles manufactured by other

Page 63: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 63

firms. Therefore, the attributes and functionalities listed in the above example define a mobile class. If we take the example of a red, 500 KB mobile of the model A2ZX of Diaz Telecommunications then it will be an example of an object of the mobile class.

Ans 3.

class mobile{

int color;

int size;

char *make;

int memory;

public:

mobile(){

color=1;

size=12;

make=”A2ZX”;

memory=200;

}

void displayDetails(){

cout<<”Color\t ”<<color<<endl;

cout<<”Size\t ”<<size<<endl;

cout<<”Make\t ”<<make<<endl;

cout<<”Memory\t ”<<memory<<endl;

}

void makeCall(int number){

Page 64: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

64 Object-Oriented Programming ©NIIT

cout<<” Calling Number ”<<number;

}

void recieveCall(int number){

cout<<”Receiving call from ”<<number;

void ring(){

cout<<”Ring Ring!!!”;

}

void remember(int number){

cout<<”Remembering ….”<<number;

}

}

int main(){

mobile myMobile;

myMobile.displayDetails();

myMobile.makeCall(9810408498);

myMobile.ring();

myMobile.receiveCall(991201010);

myMobile.remember(9901010101);

return 0;

}

Page 65: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 65

Ans 4. To emulate strcat():

char* myStringCat(char *str1, char *str2){

char *str;

str=new char(strlen(str1) + strlen(str2));

strcpy(str,str1);

for(;(str);str++);

for(;(str2);str++,str2++)

*str = *str2;

*str=’\0’;

return str;

}

To emulate strcmp():

int myStringComp(char str1[], char str2[]){

int i=0, j=0;

int value=0;

while(str1[i])

i++;

while (str2[j])

j++;

if(i==j){

for (int k=0;k<=i;k++)

if (str1[k]!=str2[k]){

value=1;

Page 66: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

66 Object-Oriented Programming ©NIIT

return value;

}

}

}

else{

if (i>j)

value=1;

else

value=-1;

}

return value;

}

To emulate strcpy():

void myStrCpy(char str1[], char str2[]){

int i=0;

while(str2[i])

i++;

for(int k=0;i>=0;i--,k++)

str1[k]=str2[i];

str[k]=’\0’;

}

Page 67: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 67

Ans 5.

class Candidate{

protected :

char name[30];

int age;

char qualification[5];

int experience;

char extraActivities[40];

private:

int score;

int interviewRating;

void acceptInterviewDetails(){

cout<<”Enter test score”;

cin>>score;

cout<<”Enter interview rating”;

cin>>interviewRating;

}

void displayInterviewDetails(){

cout<<”Test Score\t\tRating\n”;

cout<<score<<”\t\t”<<interviewRating<<endl;

}

public:

void acceptDetails(){

cout<<”Enter candidate’s name:”<<endl;

Page 68: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

68 Object-Oriented Programming ©NIIT

cin>>name;

cout<<”Enter candidate’s age:”<<endl;

cin>>age;

cout<<”Enter candidate’s qualification:”<<endl;

cin>>qualification;

cout<<”Enter candidate’s experience:”<<endl;

cin>>experience;

cout<<”Enter candidate’s extra curricular activities:”<<endl;

cin>>extraActivities;

acceptInterviewDetails();

}

void displayDetails(){

cout <<”Details of candidate :\n\n”;

cout<<”Name:”<<name<<endl;

cout<<”Age:”<<age<<endl;

cout<<”Qualification:”<<qualification<<endl;

cout<<”Experience:”<<experience<<endl;

cout<<”Extra curricular activities:”<<extraActivities<<endl;

displayInterviewDetails();

}

}

class Employee : Candiadate{

public :

void acceptDetails(){

Page 69: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 69

cout<<”Enter employee’s name:”<<endl;

cin>>name;

cout<<”Enter employee’s age:”<<endl;

cin>>age;

cout<<”Enter employee’s qualification:”<<endl;

cin>>qualification;

cout<<”Enter employee’s experience:”<<endl;

cin>>experience;

cout<<”Enter employee’s extra curricular activities:”<<endl;

cin>>extraActivities;

}

void displayDetails(){

cout <<”Details of employee :\n\n”;

cout<<”Name:”<<name<<endl;

cout<<”Age:”<<age<<endl;

cout<<”Qualification:”<<qualification<<endl;

cout<<”Experience:”<<experience<<endl;

cout<<”Extra curricular activities:”<<extraActivities<<endl;

}

}

class WrittenTest{

int mentalAbilityScore;

int reasoningScore;

int analysisScore;

Page 70: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

70 Object-Oriented Programming ©NIIT

public:

void recordtestperformance(){

cout<<”Enter test details”<<endl;

cin>>mentalAbilityScore;

cin>> reasoningScore;

cin>>analysisScore;

}

}

Ans 6. class Computer{

int speed;

int memory;

char processor[10];

char os[20];

public:

Computer(){

speed=666;

memory=128;

processor=”PentiumII”;

os=”Windows 98”;

}

}

Page 71: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 71

Ans 7.

abstract class Application{

public:

void open();

void close();

}

class Calculator:Application{

public:

void open(){

cout<<”Open called in Calculator”;

}

void close(){

cout<<”Close called in Calculator”:

}

int Calculate(int value1, int value2, int operation){

case(operation){

case 1: return (value1+value2);

break;

case 2:return (value1*value2);

break;

case 3: return (value1-value2);

break;

default: cout<<Wrong choice”;

}

Page 72: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

72 Object-Oriented Programming ©NIIT

}

}

class SpellChecker: virtual Application{

public:

void open(){

cout<<”Open called in SpellChecker”;

}

void close(){

cout<<”Close called in SpellChecker”:

}

void CheckDictionary(char *someword){

cout<<”Might be in the dictionary-have to check.”;

}

}

class SpreadSheet:Calculator, SpellChecker{

public:

void storeData(){

cout<<” Stored Data in rows and column”;

}

}

Ans 8.

class Customer{

char customerName[20];

int numberOfPeople;

Page 73: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 73

char packageCategory;

float cost;

char startDate[9];

public:

void accept_data(){

ofstream towrite(“CUSTFILE.DAT”,ios::app);

char choice=’y’;

cout<<”Want to enter details?(Y/N)”;

cin>>choice;

while((choice==’y’)||(choice==’Y’){

cout<<”Enter Customer’s Name:”;

cin>>customerName;

cout<<”Enter the number of people accompanying:”

cin>>numberOfPeople;

cout<<”Enter category of package (D/H/P) “;

cin>>packageCategory;

cout<<”Enter cost”;

cin>>cost;

cout<<”Enter start date (mm/dd/yyyy)”;

cin>>startDate;

towrite<<customerName<<numberOfPeople<<packageCategory<<cost<<startDate;

cout<<”Write more data?(Y/N)”;

cin>>choice;

Page 74: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

74 Object-Oriented Programming ©NIIT

}

towrite.close();

}

void display_data(){

char *data;

ifstream toread(“CUSTFILE.DAT”);

while(ifile){

toread.read(data);

cout<<data;

}

toread.close();

}

}

Page 75: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 75

ADDITIONAL BOOK REFERENCES Grady Booch, Object-Oriented Analysis and Design with Applications

Stephen Prata, C++ Primer Plus

Yashavant Kanetkar, Let Us C++

Yashavant Kanetkar, Pointers in C

Vijay Mukhi, The C Odyssey

Bjarne Stroustrup, The C++ Programming Language-3rd Edition

Bjarne Stroustrup, Design and Evolution of C++

Eric Naglar, Learning C++ - A Hands-on Approach

Stan Lipman and Josie LaJoie, C++ Primer – 2nd Edition

Caroll and Ellis, Reusable Programming

James Coplien, C++ Programming Styles and Idioms

Scott Myers, Effective C++

Bruce Eckel, Thinking in C++ - Volumes 1 and 2

Deitel and Deitel, How to Program in C++

Page 76: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

76 Object-Oriented Programming ©NIIT

LIST OF WEB SITES The Object-Oriented Design Method of Grady Booch –

http://panoramix.univ-paris1.fr/CRINFO/dmrg/MEE97/misop007/

Object-Oriented Really Is Better than Structured –

http://www.cs.uwa.edu.au/teaching/cs220.oop/readings1997/whyoop.html

EG3.com C++ Resource Site

http://www.cera2.com/softd/cplus.htm

C++ report columns, articles, code, and submission guidelines

http://siesta.cs.wustl.edu/~schmidt/C++-info.html

Internet sites and files of interest to C++ users

http://webnz.com/robert/cpp_site.html

Site serves as a navigator for the C++ programming language and Object-Oriented methodology resources found on the Internet

http://www.topcode.com/c++/main.shtml

Bjarne Stroustrup's Home page

http://www.research.att.com/~bs/homepage.html

Home page of the DJGPP C++ compiler.

http://www.delorie.com

GNU software page

http://www.gnu.org/software/software.html

GCC Home page

http://www.gnu.org/software/gcc/gcc.html

GNU CGI library

http://www.gnu.org/software/cgicc/cgicc.html

Win32 port for the GNU compiler

http://sourceware.cygnus.com

STL documents and Win32 ports for GNU

http://www.xraylith.wisc.edu/~khan/

Page 77: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 77

STL newbie guide

http://www.xraylith.wisc.edu/~khan/software/stl/STL.newbie.html

SGI documentation for SGI

http://www.sgi.com/Technology/STL/

Page 78: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

78 Object-Oriented Programming ©NIIT

SESSION PLAN: OBJECT-ORIENTED PROGRAMMING Cycle # Activity/Problem No. Duration (In

Mins) Cycle1

OCR1 Lesson 1: Objectives 3 Object-Oriented Methodology 26 Analysis and Design 20 Creating Classes in C++ 25 1.D.1 10 1.D.2 15 1.P.1 15 Summary 5 Total 119 OCR2 Lesson 2: Objectives 3 Variables and Datatypes 20 Writing and Executing a C++ Program 30 Introduction to Arrays 20 2.D.1 20 2.P.1 20 Summary 7 Total 120

Cycle2 OCR1 Lesson 3: Objectives 3 Access Specifiers 55 Static Variables and Functions 25 3.P.1 15 Friend Functions and Classes 15 Summary 2 Total 115 OCR2 Lesson 4: Objectives 5 Operators 10 Conditional Constructs 20 Loop Constructs 25 4.D.1 10 4.D.2 10 4.P.1 15 The Scope of a Variable 15 Summary 5 Total 115

Cycle3 OCR1 Lesson 5: Objectives 5 Initializing Objects 85 5.P.1 10 5.P.2 10 Summary 10

Page 79: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

©NIIT Object-Oriented Programming 79

Cycle # Activity/Problem No. Duration (In Mins)

Total 120 OCR2 Lesson 6: Objectives 5 Implementing Polymorphism 10 Function Overloading 20 6.D.1 20 6.P.1 10 6.P.2 10 Operator Overloading 30 Summary 5 Total 110

Cycle 4 OCR1 Overloading Unary Operators 20 Overloading Binary Operators 20 6.P.3 5 6.P.4 5 Lesson 7: Objectives 5 Identifying Relationships Between

Classes 20

Classes and Inheritance 10 7.D.1 15 7.P.1 10 Summary 5 Total 115 OCR2 Lesson 8: Objectives 5 Implementing Late Binding 80 8.D.1 20 Summary 5 Total 115

Cycle 5 OCR1 Lesson 9: Objectives 5 Introduction to Multiple Inheritance 15 Ambiguities in Multiple Inheritance 20 Invocation of Constructors and

Destructors 10

9.P.1 10 Summary 5 Total 65 Recap – Session 1-9 50 OCR2 Lesson 10: Objectives 5

Stream Class Hierarchy 3 Stream Insertion and Extraction 10 10.D.1 5 File Input and Output 28 File Open and Close 5 10.D.2 10 10.P.1 10 Open Mode Bits 5 File Pointers 15 10.D.3 5

Page 80: 02 SM1 OOP CGV1.1 - kc.niitstaff.comkc.niitstaff.com/NIITStaffUpgrade/CG/IEC Track 3...Work in the Linux environment – The student should be able to create files, navigate directories,

80 Object-Oriented Programming ©NIIT

Cycle # Activity/Problem No. Duration (In Mins)

10.P.2 10 Summary 10 Total 120

Note:

*Lesson 6 has been spilt in 2 sessions. Faculty needs to use SEM1_OOP_XP_06 (Part-1).pps and SEM1_OOP_XP_06 (Part-2).pps for the respective sessions.

Overloading Unary Operators and Overloading Binary Operators needs to be covered along with lesson- 7 and SEM1_OOP_XP_06 (Part-2).pps needs to be used for the same. After that SEM1_OOP_XP_07.pps needs to be used for lesson 7.

Suggestions:

• Lesson-10, demo 1 and 2 can be covered in CR1 and Open Mode Bits, File Pointers, Demo 3 can be covered in CR2.

OR

• In case faculty feels comfortable lesson-8 and lesson-9 can be covered in one class. And lesson-10, demo 1 and 2 can be covered in CR1 and Open Mode Bits, File Pointers, Demo 3 can be covered in CR2.