implementation of oop concept in c++

11

Click here to load reader

Upload: swarup-boro

Post on 21-May-2015

327 views

Category:

Education


4 download

DESCRIPTION

This for the students of computer science and for those who want to learn about the concepts

TRANSCRIPT

Page 1: Implementation of oop concept in c++

Page 1 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

Implementation of OOP concept in C++ The concept of OOP in c++ can be implemented through a tool found in the language called ‘Class’, therefore we should have some knowledge about class. A class is group of same type of objects or simply we can say that a class is a collection of similar type of objects. A class in c++ comprises of data and its associated functions, these data & functions are known to be the member of the class to which these belongs. Let us take a real life example. ‘A teacher teaching the students of class XII’. Here the teacher, students, teaching learning materials etc are the members of the class XII and class XII is so called a class. (Note- A ‘member variable’ and ‘member functions’ are often called ‘data member and ‘method’ respectively.) class xii //* xii is the name of the class *// { private : char teach_name[20],stud_names[20][20]; char sub[10]; Data members int chapter_no; public: void teaching(); //* member function *// }; Now next very important entity in c++ based oop is object. ‘An object is an identifiable entity with some behavior and character.’ With reference to the c++ concept we can say an object is an entty of a class therefore a class may be comprises of multiple objects, thus a class is said to be a ‘factory of objects’. In c++ object can be declared in many way. The most common to define an object in c++ is -> class xii ob; Here xii is the class name where as the object of the class xii is ‘ob’. We can also declare multiple object of the class as -> class xii ob1,ob2,ob3; The array of objects can also be declared as- class xii ob[3]; Here three objects are declared for class xii. (Note – While declaring object we can ignore the key word ‘class’.) Accessing a member of a class A class member can be access by ‘.’ (Dot) operator. Example – ob.teaching(); Here ob is an object of a class (in our example class xii) to access the member function teaching(); Visibility Mode- A member of a class can be ‘Private’,’Public’ or ‘Protected ‘ in nature. If we consider the given example, we can see two types of members are there i.e. ‘private’ and ‘public’. (Note – Default member type of a class is ‘private’) A private member of a class can not be accessed directly from the outside the class where as public member can be directly accessed. Now let us consider the visibility mode through an examplr- class sum {

Page 2: Implementation of oop concept in c++

Page 2 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

int a,b; Private members by default void read(); public : int c; void add(); void disp(); }; sum ob; Now let us see the following criteria- ob.a; ob.b; All are invalid as private members can be ob.read(); access directly. ob.c; ob.add(); All are valid as public members can be ob.disp(); access directly. To access private members we need the help of public members. i.e. we can get access to read(), a,b through public member function i.e. add() or read(). (Note – Protected members are just like private members , the only difference is ‘private members can not be inherited but protected members can be inherited. ) Definetion of Member functions of a class – A member function of a class can be defined in two different way i.e. ‘inside the class’ and/or ‘outside the class’. Let us see an example – class sum { int a,b; void read() //* Function to input the value of a and b *// { cout << “Enter two integer numbers”; cin>>a>>b; } public : int c; void add() //* Function to add() i.e. c=a+b; *// { C=a+b; } void disp(); }; void sum :: disp() { cout << “The addition of a and b is “<<c; }

Page 3: Implementation of oop concept in c++

Page 3 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

In the above example we can see that the member function read() and add() are defined (declared at the same instance) within the class where as the function named disp() is defined outside the class though declared within the class sum. (Note – The scope resolution operator (::) is used to define a member function outside the class) Now we are in a position to consider a complete program using class- //* A class based program to find out the sum of 2 integer *// # include <iostream.h> # include <conio.h> # include <stdio.h> class sum { int a,b; void read() { cout<<"Enter two integer "; cin>>a>>b; } public : int c; void add() { read(); //* The private member is called *// c=a+b; } void disp(); }; void sum :: disp() { cout<<"The addition of given 2 integer is "<<c; } void main() { clrscr(); sum ob; ob.add(); ob.disp(); getch(); } Now you can try the above program in your practical session. (Note- Member functions are created and placed in the memory when class is declared. The memory space is allocated for the object data member when objects are declared. No separate space is allocated for member functions when the objects are created.)

Page 4: Implementation of oop concept in c++

Page 4 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

Scope of class and its Members- The public member is the members that can be directly accessed by any function, whether member functions of the class or non member function of the class. The private member is the class members that are hidden from outside class. The private members implement the oop concept of data hiding. A class is known to be a global class if it defined outside the body of function i.e. not within any function. For example As stated in the aforesaid program A class is known to be a local class if the definition of the class occurs inside (body) a function. For example- void function() { ……… ……… } void main() { Class cl { //* A class declared locally*// …. …. } cl ob; } In the above example the class ‘cl’ is available only within main() function therefore it can not be obtained in the function function(). A object is said to be a global object if it is declared outside all the function bodies it means the object is globally available to all the function in the code. A object is said to be a local object if it is declared within the body of any function it means the object is available within the function and can not be used from other function. For global & local object let us consider the following example- class my_class { int a; public : void fn() { a=5; cout<<”The answer is “<<a; } } my_class ob1; // * Global object *// void kv() {

Page 5: Implementation of oop concept in c++

Page 5 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

my_class ob2; //* Local object *// } void main() { ob1.read(); //* ob1 can be used as it is global *// ob2.read(); //* ob2 can not be used as it is local *// } (Note – The private and protected member of a class can accessed only by the public member function of the class.) Object as Function Argument- As we use to pass data in the argument of a function we can pass object to a function through argument of function. An object can be passed both ways: i) By Value ii) By Reference When an object is passed by value, the function creates its own copy of the object to work with it, so any change occurs with the object within the function does not reflect to the original object. But when we use pass by reference then the memory address of the object passed to the function therefore the called function is directly using the original object and any change made within he function reflect the original object. Now let us see an example to understand the concept //* An example of passing an object by value and by reference *// # include <iostream.h> # include <conio.h> # include <stdio.h> class my_class { public : int a; void by_value(my_class cv) { cv.a=cv.a+5; cout<<"\n After pass by value"; } void by_ref(my_class &cr) { cr.a=cr.a+5; cout<<"\n After pass by reference"; } void disp(my_class di) { cout<<"The result is "<<di.a; } }; void main() { clrscr(); my_class ob,mc; ob.a=12; mc.by_value(ob); mc.disp(ob);

Page 6: Implementation of oop concept in c++

Page 6 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

mc.by_ref(ob); mc.disp(ob); getch(); } Output After pass by valueThe result is 12 After pass by referenceThe result is 17 Now you can try the above program in your practical session. Function Returning Object/ class type function- As we seen earlier that a function can return a value to a position from where it has been called, now we will see how a function can return an object . To return an object from function we have to declare the function type as class type . For example my_class fn(); Here my_class is the class name and fn() is the function name. To understand this concept let us take one programming //* An example of returning a object from a function *// # include <iostream.h> # include <conio.h> # include <stdio.h> class my_class { public : int a,b; void disp() {cout<<"\n The output is "<<a<<" & "<<b<<endl; } }; my_class fun(my_class ob2) { ob2.a=ob2.a+5; ob2.b=ob2.b+5; return (ob2); } void main() { clrscr(); my_class ob; ob.a=12; ob.b=21; ob=my_class(ob); ob.disp(); getch(); } Output The output is 12 & 21 Now you can try the above program in your practical session.

Page 7: Implementation of oop concept in c++

Page 7 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

(Note –We can assign an object to another object provided both are of same type For Example ob1=ob2 In above example same thing is happening as ob=my_class(ob); ) Inline Function- Normally when a function is called, the program stores the memory address of the instruction (function call instruction) then jumps to the memory location of the memory location. After performing the necessary operation in the called function it again jump back to the instruction memory address which was earlier stored. As we can see that it consume lot of time while to & fro jumping ,so we have inline function to get rid of it. While an inline function is called ,the complier replaces the function call statement with the function code itself and then compiles i.e. the inline function is embedded within the main process itself and thus the to & fro jumping can be ignored for time saving purpose. An inline function can be defined only prefixing a word inline at the time of function declaration. Example - inline void fn(); (Note – An inline function should be defined prior to function which calls it). (Precautionary Note- A function should be made inline only when it is small otherwise we have to sacrifice a large volume of memory against a small saving of time.) The inline function does not work under the following circumstances-

a) If the function is recursive in nature. b) If a value return type function containing loop or a switch or a goto. c) If a non value return type function containing return statement. d) If the function containing static variables.

Constant Member Functios- If a member function of a class does change any data in the class then the member function can be declared as constant member by post fixing the word const at the time of function declaration. Example- void fn() const; Nested class & Enclosing class- When a class declared within another class then declared within (inside/inner class) is called ‘Nested class’ and the outer class is called ‘Enclosing class’. Now let us see an example – class encl { int a; class nest{ … … }; … public : int b; }; In the given example ‘encl ‘ is an enclosing The class and ‘nest’ is the nested class. The object of nested class can only be declared in enclosed class. Static Class Member – In a class there may be static data member and static functions member.

Page 8: Implementation of oop concept in c++

Page 8 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

A static data member is like a global variable for its class usually meant for storing some common values. The static data member should be defined outside the class definition. The life period of the static data member remains throughout the scope of the entire program. A member function that accesses only static member (say static data member) of a class may be declared as static member function. We can declare a static member by prefixing a word static in front of the data type or function type. Now let us take an example to understand the concept. //* An example of static data member of a class *// # include <iostream.h> # include <conio.h> # include <stdio.h> class my_class { int a; static int c; public : void count(int x) { a=x; ++c; } void disp() { cout<<"\n The value of a is "<<a; } static void disp_c() { cout<<"\n The value of static data member c is "<<c; } }; int my_class :: c=0; void main() { clrscr(); my_class ob1,ob2,ob3; ob1.count(5); ob2.count(10); my_class :: disp_c(); ob3.count(15); my_class :: disp_c(); ob1.disp(); ob2.disp(); ob3.disp(); getch(); } Output The value of static data member c is 2 The value of static data member c is 3 The value of a is 5

Page 9: Implementation of oop concept in c++

Page 9 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

The value of a is 10 The value of a is 15 Now you can try the above program in your practical session. Questionnaires Answer the following Questions

1. What is the difference between a public member & private member of a class? 2. What do you mean be default member type of a class” 3. How do you access a private member of a class? 4. What is the significance of scope resolution (::) operator in class ? 5. Why inline function is discouraged to use when the function is big in volume? 6. What care should we take while defining static data member as well as static

member function of a class “ 7. What do you know about Enclosing class and Nested class? 8. Rewrite the given program after correcting all errors.

Class student { int age; char name[25]; student(char *sname, int a) { strcpy(name, sname); age=a; } public: void display() { cout<<”age=”<<age; cout<<”Name=”<<name; } }; student stud; student stud1(“Rohit”, 17); main() { ------- ------ }

9. What will be the output of the following code: #include<iostream.h> clasws dube { int heingt, width, depth; public: void cube() {

Page 10: Implementation of oop concept in c++

Page 10 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

void cube(int ht, int wd, int dp) { height=ht; width=wd; depth=dp; } int volume() { return height * width * depth;

} 10. Define a class ELECTION with the following specifications . Write a suitable

main ( ) function also to declare 3 objects of ELECTION type and find the winner and display the details .

Private members : Data : candidate_name , party , vote_received Public members : Functions : enterdetails ( ) – to input data Display ( ) – to display the details of the winner Winner ( ) – To return the details of the winner trough

the object after comparing the votes received by three candidates. 11. Rewrite the following program after removing all error(s), if any. ( make underline for correction) include<iostream.h> class maine { int x; float y; protected; long x1; public: maine() { }; maine(int s, t=2.5) { x=s; y=t; } getdata() { cin>>x>>y>>x1; } void displaydata() { cout<<x<<y<<x1; } }; void main() { clrscr(); maine m1(20,2.4); maine m2(1); class maine m3; } 12. Define a class Competition in C++ with the following descriptions:

Page 11: Implementation of oop concept in c++

Page 11 of 11

Prepared By Sumit Kumar Gupta, PGT Computer Science

Data Members Event_no integer

Description char(30) Score integer qualified char

Member functions A constructor to assign initial values Event No number as 101, Description as “State level” Score is 50, qualified ‘N’.