SlideShare uma empresa Scribd logo
1 de 11
Baixar para ler offline
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 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 {

                          Prepared By Sumit Kumar Gupta, PGT Computer Science
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
          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;
        }




                          Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 11

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.)


                        Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 4 of 11



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()
                             {

                           Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 5 of 11

                                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);

                         Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 6 of 11

               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.


                          Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 7 of 11

(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.

                         Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 8 of 11


 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

                          Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 9 of 11

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()
             {

                         Prepared By Sumit Kumar Gupta, PGT Computer Science
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
Page 11 of 11

 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’.




                  Prepared By Sumit Kumar Gupta, PGT Computer Science

Mais conteúdo relacionado

Mais procurados

OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
Mohamed Essam
 
Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++
Deepak Singh
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 

Mais procurados (20)

Friend function
Friend functionFriend function
Friend function
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Constructor
ConstructorConstructor
Constructor
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
programming in C++ report
programming in C++ reportprogramming in C++ report
programming in C++ report
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Inline function
Inline functionInline function
Inline function
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 

Destaque

01 computer communication and networks v
01 computer communication and networks v01 computer communication and networks v
01 computer communication and networks v
Swarup Kumar Boro
 
#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance
Hadziq Fabroyir
 

Destaque (20)

Chapter1 Introduction to OOP (Java)
Chapter1 Introduction to OOP (Java)Chapter1 Introduction to OOP (Java)
Chapter1 Introduction to OOP (Java)
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Concept
 
Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \
 
object oriented programming(syed munib ali 11b-023-bs)
object oriented programming(syed munib ali 11b-023-bs)object oriented programming(syed munib ali 11b-023-bs)
object oriented programming(syed munib ali 11b-023-bs)
 
Oop l2
Oop l2Oop l2
Oop l2
 
C++ Programming : Learn OOP in C++
C++ Programming : Learn OOP in C++C++ Programming : Learn OOP in C++
C++ Programming : Learn OOP in C++
 
Overview- Skillwise Consulting
Overview- Skillwise Consulting Overview- Skillwise Consulting
Overview- Skillwise Consulting
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_concept
 
2-D array
2-D array2-D array
2-D array
 
Pointers
PointersPointers
Pointers
 
1-D array
1-D array1-D array
1-D array
 
File handling
File handlingFile handling
File handling
 
Unit 3
Unit  3Unit  3
Unit 3
 
Functions
FunctionsFunctions
Functions
 
01 computer communication and networks v
01 computer communication and networks v01 computer communication and networks v
01 computer communication and networks v
 
java Oops.ppt
java Oops.pptjava Oops.ppt
java Oops.ppt
 
Oop design principles
Oop design principlesOop design principles
Oop design principles
 
Stack
StackStack
Stack
 
#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance
 

Semelhante a Implementation of oop concept in c++

C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
krismishra
 

Semelhante a Implementation of oop concept in c++ (20)

Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
ccc
cccccc
ccc
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
Class and object
Class and objectClass and object
Class and object
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
 
C++ Notes
C++ NotesC++ Notes
C++ Notes
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
 
C questions
C questionsC questions
C questions
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 

Mais de Swarup Kumar Boro (18)

c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
c++ program for Canteen management
c++ program for Canteen managementc++ program for Canteen management
c++ program for Canteen management
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Queue
QueueQueue
Queue
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Computer science study material
Computer science study materialComputer science study material
Computer science study material
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
computer science sample papers 3
computer science sample papers 3computer science sample papers 3
computer science sample papers 3
 
computer science sample papers 1
computer science sample papers 1computer science sample papers 1
computer science sample papers 1
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
 
Boolean algebra laws
Boolean algebra lawsBoolean algebra laws
Boolean algebra laws
 
Class
ClassClass
Class
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
Physics
PhysicsPhysics
Physics
 
Physics activity
Physics activityPhysics activity
Physics activity
 

Último

Último (20)

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 

Implementation of oop concept in c++

  • 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 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 { Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 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 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; } Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 3. Page 3 of 11 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.) Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 4. Page 4 of 11 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() { Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 5. Page 5 of 11 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); Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 6. Page 6 of 11 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. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 7. Page 7 of 11 (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. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 8. Page 8 of 11 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 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 9. Page 9 of 11 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() { Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 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. Page 11 of 11 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’. Prepared By Sumit Kumar Gupta, PGT Computer Science