Implementation of oop concept in c++


Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Implementation of oop concept in c++

  1. 1. Page 1 of 11 Implementation of OOP concept in C++The concept of OOP in c++ can be implemented through a tool found in the languagecalled ‘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 acollection 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’. Herethe teacher, students, teaching learning materials etc are the members of the classXII and class XII is so called a class. (Note- A ‘member variable’ and ‘member functions’ are often called ‘data memberand ‘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 classtherefore 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 objectin 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; Thearray 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 classA 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 memberfunction 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 classwhere as public member can be directly accessed.Now let us consider the visibility mode through an examplr- class sum { Prepared By Sumit Kumar Gupta, PGT Computer Science
  2. 2. Page 2 of 11 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; 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 getaccess 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 theclass’ 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; } Prepared By Sumit Kumar Gupta, PGT Computer Science
  3. 3. Page 3 of 11In the above example we can see that the member function read() and add() aredefined (declared at the same instance) within the class where as the functionnamed disp() is defined outside the class though declared within the class sum.(Note – The scope resolution operator (::) is used to define a member functionoutside 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 isdeclared. The memory space is allocated for the object data member when objectsare declared. No separate space is allocated for member functions when the objectsare created.) Prepared By Sumit Kumar Gupta, PGT Computer Science
  4. 4. Page 4 of 11Scope 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 functioni.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 thereforeit can not be obtained in the function function(). A object is said to be a global object if it is declared outside all the functionbodies 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 functionit means the object is available within the function and can not be used from otherfunction. 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() { Prepared By Sumit Kumar Gupta, PGT Computer Science
  5. 5. Page 5 of 11 my_class ob2; //* Local object *// } void main() {; //* ob1 can be used as it is global *//; //* ob2 can not be used as it is local *// } (Note – The private and protected member of a class can accessed only by thepublic 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 afunction through argument of function. An object can be passed both ways: i) By Value ii) By ReferenceWhen an object is passed by value, the function creates its own copy of the object towork with it, so any change occurs with the object within the function does notreflect to the original object. But when we use pass by reference then the memoryaddress of the object passed to the function therefore the called function is directlyusing the original object and any change made within he function reflect the originalobject. 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); Prepared By Sumit Kumar Gupta, PGT Computer Science
  6. 6. Page 6 of 11 mc.by_ref(ob); mc.disp(ob); getch(); }OutputAfter pass by valueThe result is 12After 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 hasbeen 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 asclass 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();} OutputThe output is 12 & 21Now you can try the above program in your practical session. Prepared By Sumit Kumar Gupta, PGT Computer Science
  7. 7. Page 7 of 11(Note –We can assign an object to another object provided both are of same typeFor 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 theinstruction (function call instruction) then jumps to the memory location of thememory location. After performing the necessary operation in the called function itagain jump back to the instruction memory address which was earlier stored. As wecan see that it consume lot of time while to & fro jumping ,so we have inlinefunction to get rid of it. While an inline function is called ,the complier replaces the function call statementwith the function code itself and then compiles i.e. the inline function is embeddedwithin the main process itself and thus the to & fro jumping can be ignored for timesaving purpose. An inline function can be defined only prefixing a word inline atthe 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 smallotherwise we have to sacrifice a large volume of memory against a small saving oftime.)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 themember function can be declared as constant member by post fixing the word constat 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. Prepared By Sumit Kumar Gupta, PGT Computer Science
  8. 8. Page 8 of 11 A static data member is like a global variable for its class usually meant for storingsome common values. The static data member should be defined outside the classdefinition. The life period of the static data member remains throughout the scope ofthe entire program. A member function that accesses only static member (say static data member) ofa class may be declared as static member function.We can declare a static member by prefixing a word static in front of the data typeor 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(); }OutputThe value of static data member c is 2The value of static data member c is 3The value of a is 5 Prepared By Sumit Kumar Gupta, PGT Computer Science
  9. 9. Page 9 of 11The value of a is 10The value of a is 15Now you can try the above program in your practical session. QuestionnairesAnswer 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() { Prepared By Sumit Kumar Gupta, PGT Computer Science
  10. 10. Page 10 of 11 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: Prepared By Sumit Kumar Gupta, PGT Computer Science
  11. 11. Page 11 of 11 Data MembersEvent_no integerDescription char(30)Score integerqualified char Member functions A constructor to assign initial values Event No number as 101, Description as “State level” Score is 50, qualified ‘N’. Prepared By Sumit Kumar Gupta, PGT Computer Science