Oops

26
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M) Class: XII C++ Basics of Object Oriented Programming (OOPS) IMPORTANT TERMS & DEFINITIONS 1. OOP. Object Oriented Programming enables the programmers to group together data and the code that uses data into discrete units. In OOP the stress is given on object in spite of procedure. 2. Procedural Programming. In procedural programming, we think about functions and the execution flow through these functions. 3. Object. An object is a self contained abstraction of an item. An instance of a class. 4. Class. A class is user defined data type used to implement an abstract object. It contains members of three types: private, public and protected. By default the data members of the class and private. Classes enable the programmer to model objects with attributes and behaviours. Class type can be defined in C++ using the keyword class and struct, but keyword class is normally used for this purpose. 5. Class declaration. The class is declared with a keyword class: class <class_name> { private : data_members; member_functions; [public : data_members; member_functions; protected: data_members; member_functions;] }; 6. Members. There are two kinds of members in the class. First, data members and the second and members functions. Member access specifiers always end with a colon (;) and can appear multiple times and in any order in a class definition. 7. Data members. Data members are exactly like the variables in a structure. Data members of a class are normally made private and members functions of a class are normally made public. Some member functions may be private and serve as utility functions to the other functions of the class. 8. Private section. Private members are available to only members of class and not accessible to functions outside the class. The default access mode for classes is private so all members after the 1

description

C++ Programming NOTES , object oriented programming , OOPS , Assignment , C++ , 12th CBSE

Transcript of Oops

Page 1: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

IMPORTANT TERMS & DEFINITIONS

1. OOP. Object Oriented Programming enables the programmers to group together data and the code that uses data into discrete units. In OOP the stress is given on object in spite of procedure.

2. Procedural Programming. In procedural programming, we think about functions and the execution flow through these functions.

3. Object. An object is a self contained abstraction of an item. An instance of a class.4. Class. A class is user defined data type used to implement an abstract object. It contains members of

three types: private, public and protected. By default the data members of the class and private. Classes enable the programmer to model objects with attributes and behaviours. Class type can be defined in C++ using the keyword class and struct, but keyword class is normally used for this purpose.

5. Class declaration. The class is declared with a keyword class:class <class_name>{ private :

data_members;member_functions;

[public :data_members;

member_functions;protected:

data_members;member_functions;]

};6. Members. There are two kinds of members in the class. First, data members and the second and

members functions. Member access specifiers always end with a colon (;) and can appear multiple times and in any order in a class definition.

7. Data members. Data members are exactly like the variables in a structure. Data members of a class are normally made private and members functions of a class are normally made public. Some member functions may be private and serve as utility functions to the other functions of the class.

8. Private section. Private members are available to only members of class and not accessible to functions outside the class. The default access mode for classes is private so all members after the class header and before the first member access specifiers are considered to be private.

9. Public section. Any member following public keyword can be accessed from outside the class. public members of a class present a view of the services the class provides to the clients of the class.

10. Scope resolution operator (::). This operator is used in situations where a global variable exists with the same name as a local variable. Also, this is used in C++ class when the member functions are declared outside the class definition; the function name is preceded by the class name and the binary scope resolution operator (::).

11. Data hiding. The variables and functions declared in a class as private are not accessible to any outside function. This feature of class declaration is called data hiding.

12. Abstract data type. The data type, which ties the data and its associated function into a single unit, is called Abstract Data Type (ADT). Otherwise, Abstract Data Types are the data types, which represent the required features of an item without including any background details, e.g.; class.

13. Encapsulation. Combining data and the required procedures to manipulate this data into a single entity is known as encapsulation. This is an essential concept of OOP’s which is implemented through classes.

14. Abstraction. The class member which are private remains hidden from outside world, the public members from the interface by providing the essential and relevant information to outside world. Thus only the essential features are represented to outside world without including the background details, which is called abstraction.

1

Page 2: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

15. Inline functions. A function is defined as being inline, its implementation is substituted into the code where the function call was made.

16. Friend function. A function outside of a class can be defined to be a friend function by the class which gives the friend, free access to the private members of the class.

BASIC CONCEPT

1. OOP CONCEPT

(i) DATA – ABSTRACTION : It is the act of representing the essential features with including the background details and explanations.

(ii) DATA – HIDING : It is related concept to data abstraction. Unessential features or background details are hidden from the world

(iii) DATA – ENCAPSULATION : Wrapping up of data and associated functions in one single unit. Encapsulation implements abstraction also.

(iv) INHERITANCE : It is capability of one class to inherit properties from another class. The class which is inherited is base class and known as SUPER CLASS, and the class which inherits from other class is called derived class or subclass.]

(v) POLYMORPHISM : It is ability for a message or data to be processed in more than one form. Polymorphism is a property by which the same message can be sent to objects of several class.

(vi) OBJECT : It represents an identifiable entity with some characteristics and behaviour.

2. IMPLEMENTATION IN C++ Sales Persongeneric medical history ABSTRACTION FOR SALES SYSTEM history Commission rate Cars sold family Cars sold

Commission ratetalents

Credit name namerecord

real world

ELECTRIC SWITCH BOARD (from real world entity) is example, where the internal connections like wiring etc are not shown, hence it just shows the essential features with some abstraction.

Real world objects have Physical characteristics (State) and behaviour (eg) a motor bike hasCharacteristics → Current gear, wheels etcBehaviour → braking, accelerating, charging years etc

In Software objects, state is maintained through variables or data items and behaviour is implemented through functions (known as methods)

abstraction Real world {data, data, - - - - - - }

{method, method, - - - - }

2

attributeentity

behaviour

Page 3: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

A class binds together data and its associated functions under one unit and hence implement encapsulation, as encapsulation means wrapping up data and associated functions together into a single unit.

A class groups its members into three sections : private, protected and Public: The private and protected members remain hidden from outside world. Thus through private and protected members, a class enforces data-hiding.

General structure of a C++ class implements OOP concept {data, data

…..}

{method, method, ….}

A class is defined asClass < class name >{private : // hidden data members / methods hereprotected : // (unimportant implementation details)Public : // exposed important details} ;

* BENEFITS OF ENCAPSULATION

1. MODULARITY : * Source code can be written & maintained independently* An object can passed easily around

2. INFORMATION :* An object has a public interface for other objects to communicate with HIDING * An object can maintain private information and methods that can be changed

without affecting other objects.

* WHEN YOU WANT TO CHANGE GEARS ON MOTOR BIKE, YOU DON’T NEED TO KNOW HOW A METHOD IS IMPLEMENTED, YOU JUST NEED TO KNOW WHICH METHOD TO INVOKE AND ITS INTERFACE WITHOUT NEED TO KNOW HOW A METHOD IS IMPLEMENTED

* INHERITANCE, is implemented by specifying the name of the BASE CLASS FROM WHICH THE CLASS BEING DEFINED (the derived class) has to inherit from.

Class < derived class name > : < base class name >{ derived class own features }

* GRAND FATHER

FATHER Inheritance is real world entity

SON

3

Private

Protected

Public

Page 4: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

* SHAPE → is ABSTRACT CLASS, it suggests a state like colour, size etc. It does not specify how to implement interface like surface area, volume, perimeter etc.

HOW WOULD YOU CALCULATE AREA OF SHAPE?ANSWER: WHICH SHAPE?

FROM SHAPE CLASS, OTHER Classes like circle class, rectangle class, triangle class inherit. These classes are CONCRETE CLASSES, As they provide proper functionality for its members functions

* POLYMORPHISM allows one interface to be used with different situation

* Polymorphism is implemented with the help of FUNCTION-OVERLOADING

* A FUNCTION NAME HAVING SEVERAL DEFINITIONS THAT ARE DIFFERENTIABLE BY THE NUMBER OR TYPES OF THEIR ARGUMENTS, IS KNOWN AS OVERLOADED FUNCTION AND THIS PROCESS IS KNOWN AS FUNCTION OVERLOADING

* FUNCTION OVERLOADING implements polymorphism and it also reduces number of comparisons in a program to make it run faster

Consider,void see_day FUNCTION 1{cout << “can see through Daylight” ;}void see_night ( ) FUNCTION 2{

cout << “can’t see through darkness” ;}

In such cases, it is to be decided upon which function should be executed, for example

if (choice = = ‘D’ )see_day ( ) ; // calling of functn1

elseif (choice = = ‘N’)

see_night ( ) ; // calling of functn2

4

Draw ( )

Draw-circle ( )

Draw-square ( )Draw-Rectangle ( )

Page 5: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

Example of FUNCTION-OVERLOADING

void prnsqr (int i) F1( ){

Function cout << “integers square is “<< i * i ;name prnsqr ( ) }is same, but void prn sqr (char c) F2( )their arguments {are different cout << “No square for character” ,

}void prn sqr (float f) F3( ){cout << “float’s squre is” << f * f ;

Calling of these functions→ prnsqr (‘z’) ; // calls F2( )→ prnsqr (13) ; // calls F1( ) → prnsqr (134-52); // calls F3( )

ADVANTAGES OF OOP (very important)

1. RE-USE OF OOP2. Ease of Comprehension3. Ease of fabrication and maintenance4. Easy redesign and extension

ASSIGNMENTQ1. How are data and functions organized in Object Oriented Program?Q2. Identify the error(s) in the following code-fragment:

class X { int a b; void count (void) { a++ ; }

public :int X,void init (int, int, int);void print (void);};

void X :: init(int i, int j, int k) { a = i;

b = j; x = k;

void X :: print (void) { count ( );

cout << “a =” << a ; << “ b =” << b<< “ x =” << x << “\n” ; }void func(void);X 01;int main ( ) { X 02;

01.init (0, 1, 2); 02.init (2, 3, 4);

5

Page 6: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

03.init (9, 10, 11); 03.a = 03 . b = 03 . x, 01.count ( ); 02.count ( ); 03.count ( ); 01.print ( ); 02.print ( ); 03.print ( );

}

Q32. Identify the error(s) in the following code fragment :int x = 5;int y = 3;class Outer {

public :int x ;int a;static int s;class Inner { int a ;

public :void f (int i){ x = i;

s = i;y = i;a = i;

}} ; //Inner definition over

//Inner objectInner I1;void g(int i){ x = i ;

y = i ;a = i ;s = i ;

} }; //outer definition overOuter O1;int main ( ) {O1.l1.f(3); //statement1

O1. g(8);return 0;

}What will be the values of ::x, ::y, Outer::x, Outer::a, Outer::s, Inner::a after statement 1 and statement 2 of above code?

Q4. Given the following code fragment : include <iostream.h>class X {

int x, y;void count (void);

public :int a, b ;

6

Page 7: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

void getval (int, int) ;void prval (void) ;

} ;:: //X’s member functions’ definitions:X 01 ;int main ( ){ class y { int i, j ;

void abc (void) ;public :

float k ;void get(void) ;void prin(void) ;

};Y 02 ;X 03 ;:} //end main ( )void func1 ( ) ;{ X 04; : } //end fun1( )void func2( ) { : { : //end func2( )

Which all members (data & functions) of classes X and Y can be accessed by main ( ), fun1 ( ) and func2( )? Give reasons.

Q5. Define a class to represent a book in a library. Include the following members :Data MembersBook Number, Book Name, Author, Publisher, Price, No. of Copies, No. of copies issuedMember Functions(i) To assign initial values (ii) To issue a book after checking for its availability(iii) To return a book (iv) To display book information.

Q6. Declare a class to represent fixed-deposit account of 10 customers with the following data members:Name of the depositor, Account Number, Time Period (1 or 3 or 5 years), Amount. The class also contains following member functions:(a) To initialise data members.(b) For withdrawal of money (after half of the time period has passed).(c) To display the data members.

Q7. Define a class to represent batsmen in a cricket team. Include the following members ;Data MembersFirst name, Last name, Runs made, Number of fours, Number of sixes,Member Functions(i) To assign the initial values(ii) To update runs made

(It should simultaneously update fours and sixes, if required).(iii) To display the batsman’s information.Make appropriate assumptions about access labels.

7

Page 8: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

Q8. Define a class to represent bowlers in a cricket team. Include the following members :Data MembersFirst name, Last name, Overs bowled, Number of Maiden overs, Runs given, Wickets taken.Member Functions(i) To assign the initial values(ii) To update the information(iii) To display the bowler’s informationMake appropriate assumptions about access specifies.

Q9. Write a program to manage a room’s statistics. The room class includes the following members:Data MembersLength, Width, HeightMember Functions(i) To assign initial values (ii) To calculate area(iii) To display information (length, width, height & area)

Q10. Modify the above program so that length, width and height become objects of class distance that includes:Data MembersMeters, CentimetersMemory Functions (i) To assign values (ii) To print values.

Q11. Declare a class to represent bank account of 10 customers with the following data members. Name of the depositor, Account number, Type of account, (S for Savings and C for Current). Balance account. The class also contains members functions to do the following:(i) To initialize data members(ii) To deposit money(iii) To withdraw money after checking the balance (minimum balance in Rs. 1000)(iv) To display the data members

[Note: You are also required to give detailed function definitions.]

Q12. Define a class worker with the following specification:Private members of class worker

wname 25 charactershrwrk, wgrate float (hours worked and wagerated per hour)totwage float(hrwrk * wgrate)_calcwg( ) A function to find hrwk * wgrate with float return type

Public members of class workerin_data( ) a function to accept values for wno, wname, hrwrk, wgrate and invoke

calcwg( ) to calculate totwage.out_data( ) a function to display all the data members on the screen you should

give definitions of functions.

Q13. Define a class Teacher with the following specification:private members :

name 20 characterssubject 10 charactersBasic, DA, HRA floatSalary float

Calculate ( ) function computes the salary and returns it.Salary is sum of Basic, DA and HRA

8

Page 9: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

public members:Readdata( ) function accepts the data values and invoke the calculate functionDisplaydata( ) function prints the data on the screen.

Q14. Define a class Student with the following specification:private members:

roll_no integername 20 charactersclass 8 charactersmarks [5] integerpercentage float

Calculate( ) function that calculates overall percentage of marks and returns the percentage of marks.public members:Readmarks( ) a function that reads marks and invokes the calculate function Displaymarks( ) a function that prints the marks.

Q15. Define a class employee with the following specifications:private members of class employee

empno integerename 20 characterbasic, hra, da floatnetpay floatcalculate( ) A function to find basic + hra + da with float return type

public member function of class employeehavedata( ) function to accept values for empno, ename, basic, hra, da and invokecalculate( ) to calculate netpay.dispdata( ) function to display all the data members on the screen

Q16. Define a class BOOK with the following specification :Private members of the class BOOK areBOOK_NO integer typeBOOK_TITLE 20 charactersPRICE float (price per copy)TOTAL_COST ( ) A function to calculate the total cost for N number of copies, where N

is passed to the function as argumentPublic members of the class BOOK areINPUT( ) Function to read BOOK_NO, BOOK_TITLE, PRICEPURCHASE( ) Function to ask the user to input the number of copies to be purchased.

It invokes TOTAL COST( ) and prints the total cost to be paid by the user.

Note: You are also required to give detailed function definitions.

Q17. Declare a class to represent bank account of 10 customers with the following data members. Name of the depositor, Account number, Type of account, (S for Savings and C for Current), Balance amount. The class also contains member functions to do the following:(i) To initialize data members (ii) To deposit money(iii) To withdraw money after checking the balance (minimum balance in Rs. 1000)(v) To display the data membersNote: You are also required to give detailed function definitions.

Q18. What are advantages and disadvantages of inline functions?

9

Page 10: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

Q19. Identify the errors in the following code fragment :class X {

int x;static int ctr;

public :void init (void){ x = xtr = 0;}static void prn(void){ cout << ctr << x ;

};:

Q20. Identify and correct the errors in the following code fragment :class X {static int a;

int b; char c ;

public static float x,

float y, void getval (int i, int j, char k) { a = i ;

b = j ;c = k ;x = y = 0 ;

} void prn (void) } cout < < a < < b < < c < < x < < y < < “\n” ; } };

Q21. Define a class student with the following specifications:private members of class student

admno integersname 20 charactereng, math, science floattotal floatctotal( ) A function to calculate eng + math + science with float return type

public member functions of class studentTakedata( ) function to accept values for admno, sname, eng, math, science and invoke ctotal( ) to calculate total. Showdata( ) function to display all the data members on the screen

Q22. Write the output of the following program.include <isostream.h>class Counter{ private :

unsigned int count ;public :

Counter( ) {count = 0 ; }void inc_Count( ) {count ++ ;}int get_Count( ) {retu’n count ;}

} ;

10

Page 11: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

void main( ){ Counter C1, C2 ;

cout << “\n C1 =” << C1 get_Count( ) ;cout << “\n C2 =” << C2.get_Count( ) ;C1.inc_Count( ) ;C2.inc_Count( ) ;C2.inc_Count( ) ;cout << “\nC1 =” << C1.get_Count( ) ;cout << “\nC2 =” << C2.get_Count( ) ;

}

Q23. Identify the errors in following program segmentclass abc{

public int read( );char display val( );

private:int x ;char choice;

}

Q24. What is wrong with the following clas declaration:{

int a, b;pubic

void read( );}

Q25. Identify the errors in the following program code :include <iostream.h>class myclass {

int a, b;public:

void set(int I, int j) {a = I; b = ;}void show( ) { cout <<a << ‘ ‘ << b << ‘\n’;

} ;class yourclass {

int a, b;public:

void set(int I, int j) {a = I; b = j;}void show( ) { cout << a << ‘ ‘ << b << ‘\n’;

};int main(){

myclass 01 ;yourclass 02;o1.set(10, 4);o2 = 01 ;o1.show();o2.show();return 0;

}

11

Page 12: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

Q26. Identify the errors in the following program segment:include <iostream.h>class myclass {

int a;public:void set_a(int num);int get_a();

};void myclass:set_a(int num0{

a = num;}int myclass::get_a(){

return a;}int main(){

myclass ob1, ob2;ob1.a = 10;ob2.a = 99;cout << ob1.get_a( ) << endl;cout << ob2.get_a( ) << endl;return 0;

}

Q27. Rewrite the given program after correcting all errors.Class Student{

int age;char name[25];student(car *sname, int a){

strcpy(name, sname);age = a;

}public:

void display(){

cout <<”age = “<< age;cout << “Name = “<< name;

}};Student stud;student stud 1(“Rohit”, 17);main(){

}

12

Page 13: Oops

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ Basics of Object Oriented Programming (OOPS)

Q28. Identify the errors in the following program segment:class X{

public:int a, b;void intial(){ a = b = 0; }float sum();float sqr();

};float sum(){

return a + b;}float sqr(){

return sum() * sum();}

Q29. Identify the errors in the following program segment:Class X{

static int a,b,c;void read(int I, int j, char k){

a = I;b = j;c = k;x = y = 0;

}void display(){

cout << a << b << c << x << y << endl;}

};

Q30. Declare a class employee having following members:Data Members:

Employee nameEmployee addressEmployee number

Member Functions:To read data membersTo display the data members

13