SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Downloaden Sie, um offline zu lesen
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];
int chapter_no;
public:
void teaching(); //* member function *//
};

Data members

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 ModeA 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 examplrclass sum {

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 2 of 11
int a,b;
void read();
public :
int c;
void add();
void disp();
};
sum ob;

Private members by default

Now let us see the following criteriaob.a;
ob.b;
ob.read();
ob.c;
ob.add();
ob.disp();

All are invalid as private members can be
access directly.

All are valid as public members can be
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 MembersThe 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 examplevoid 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 exampleclass 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 ArgumentAs 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 functionAs 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 FunctionNormally 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 circumstancesa) 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 FunctiosIf 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 classWhen 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

Weitere ähnliche Inhalte

Was ist angesagt?

Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3C# Learning Classes
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++Vishnu Shaji
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++sandeep54552
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++jehan1987
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three noskrismishra
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismJawad Khan
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)farhan amjad
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3Shaili Choudhary
 

Was ist angesagt? (20)

Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
C++ oop
C++ oopC++ oop
C++ oop
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
 
Class and object
Class and objectClass and object
Class and object
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphism
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 
C++ classes
C++ classesC++ classes
C++ classes
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 

Andere mochten auch

C++ revision tour
C++ revision tourC++ revision tour
C++ revision tourSwarup Boro
 
Spider Man Takes A Day Off
Spider Man Takes A Day OffSpider Man Takes A Day Off
Spider Man Takes A Day Offchrisregan501
 
Railway reservation
Railway reservationRailway reservation
Railway reservationSwarup Boro
 
Helping men with their anger
Helping men with their angerHelping men with their anger
Helping men with their angerAlan MacKenzie
 
Declaracao Ministerio-Certificado FinalUGS
Declaracao Ministerio-Certificado FinalUGSDeclaracao Ministerio-Certificado FinalUGS
Declaracao Ministerio-Certificado FinalUGSCarlos Spranger
 
The HSMAI Region Europe Mentor Programme
The HSMAI Region Europe Mentor ProgrammeThe HSMAI Region Europe Mentor Programme
The HSMAI Region Europe Mentor ProgrammeHSMAIeurope
 
Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru
Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru
Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru АКМР Corpmedia.ru
 
UTS: INSEARCH 2014 international guide
UTS: INSEARCH 2014 international guideUTS: INSEARCH 2014 international guide
UTS: INSEARCH 2014 international guideIdpeducation Vietnam
 
MyCerebro Solution Overview
MyCerebro Solution OverviewMyCerebro Solution Overview
MyCerebro Solution OverviewArlene Gunio
 
Bba Colleges In Kolkata | Sbihm
Bba Colleges In Kolkata | SbihmBba Colleges In Kolkata | Sbihm
Bba Colleges In Kolkata | SbihmManagement09
 
Social Media & Social Learning for Learning Professionals
Social Media & Social Learning for Learning ProfessionalsSocial Media & Social Learning for Learning Professionals
Social Media & Social Learning for Learning ProfessionalsDavid Kelly
 

Andere mochten auch (16)

C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Spider Man Takes A Day Off
Spider Man Takes A Day OffSpider Man Takes A Day Off
Spider Man Takes A Day Off
 
Railway reservation
Railway reservationRailway reservation
Railway reservation
 
Boolean
BooleanBoolean
Boolean
 
Prova prova prova
Prova prova provaProva prova prova
Prova prova prova
 
Helping men with their anger
Helping men with their angerHelping men with their anger
Helping men with their anger
 
Sc
ScSc
Sc
 
Declaracao Ministerio-Certificado FinalUGS
Declaracao Ministerio-Certificado FinalUGSDeclaracao Ministerio-Certificado FinalUGS
Declaracao Ministerio-Certificado FinalUGS
 
The HSMAI Region Europe Mentor Programme
The HSMAI Region Europe Mentor ProgrammeThe HSMAI Region Europe Mentor Programme
The HSMAI Region Europe Mentor Programme
 
Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru
Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru
Digital AWARDS 2016. Онлайн-кинотеатр Tvzavr.ru
 
Sustraccion informal
Sustraccion informalSustraccion informal
Sustraccion informal
 
UTS: INSEARCH 2014 international guide
UTS: INSEARCH 2014 international guideUTS: INSEARCH 2014 international guide
UTS: INSEARCH 2014 international guide
 
MyCerebro Solution Overview
MyCerebro Solution OverviewMyCerebro Solution Overview
MyCerebro Solution Overview
 
Cultura febrero 16
Cultura febrero 16Cultura febrero 16
Cultura febrero 16
 
Bba Colleges In Kolkata | Sbihm
Bba Colleges In Kolkata | SbihmBba Colleges In Kolkata | Sbihm
Bba Colleges In Kolkata | Sbihm
 
Social Media & Social Learning for Learning Professionals
Social Media & Social Learning for Learning ProfessionalsSocial Media & Social Learning for Learning Professionals
Social Media & Social Learning for Learning Professionals
 

Ähnlich wie Implementation of oop concept in c++

Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Kumar Boro
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfstudy material
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 
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)Abu Saleh
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ Dev Chauhan
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.pptBArulmozhi
 
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 & objectsRai University
 
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 & objectsRai University
 

Ähnlich wie 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++
 
Class and object
Class and objectClass and object
Class and object
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
ccc
cccccc
ccc
 
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
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdf
 
C++ Notes
C++ NotesC++ Notes
C++ Notes
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
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)
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
Lecture 2 (1)
Lecture 2 (1)Lecture 2 (1)
Lecture 2 (1)
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
My c++
My c++My c++
My c++
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 
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
 
class c++
class c++class c++
class c++
 
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
 

Mehr von Swarup Boro

Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Swarup Boro
 
Program: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsProgram: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsSwarup Boro
 
Array using recursion
Array using recursionArray using recursion
Array using recursionSwarup Boro
 
Binary addition using class concept in c++
Binary addition using class concept in c++Binary addition using class concept in c++
Binary addition using class concept in c++Swarup Boro
 
Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids                                 Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids Swarup Boro
 
Program using function overloading
Program using function overloadingProgram using function overloading
Program using function overloadingSwarup Boro
 
Program to sort array using insertion sort
Program to sort array using insertion sortProgram to sort array using insertion sort
Program to sort array using insertion sortSwarup Boro
 
Program to find the avg of two numbers
Program to find the avg of two numbersProgram to find the avg of two numbers
Program to find the avg of two numbersSwarup Boro
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a numberSwarup Boro
 
Canteen management program
Canteen management programCanteen management program
Canteen management programSwarup Boro
 
C++ program using class
C++ program using classC++ program using class
C++ program using classSwarup Boro
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSwarup Boro
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functionsSwarup Boro
 
Structures in c++
Structures in c++Structures in c++
Structures in c++Swarup Boro
 
Computer communication and networks
Computer communication and networks Computer communication and networks
Computer communication and networks Swarup Boro
 

Mehr von Swarup Boro (20)

Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Concatenation of two strings using class in c++
Concatenation of two strings using class in c++
 
Program: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsProgram: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 students
 
Array using recursion
Array using recursionArray using recursion
Array using recursion
 
Binary addition using class concept in c++
Binary addition using class concept in c++Binary addition using class concept in c++
Binary addition using class concept in c++
 
Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids                                 Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids
 
Program using function overloading
Program using function overloadingProgram using function overloading
Program using function overloading
 
Program to sort array using insertion sort
Program to sort array using insertion sortProgram to sort array using insertion sort
Program to sort array using insertion sort
 
Program to find the avg of two numbers
Program to find the avg of two numbersProgram to find the avg of two numbers
Program to find the avg of two numbers
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a number
 
Canteen management program
Canteen management programCanteen management program
Canteen management program
 
C++ program using class
C++ program using classC++ program using class
C++ program using class
 
Classes
ClassesClasses
Classes
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Pointers
PointersPointers
Pointers
 
Queue
QueueQueue
Queue
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Stack
StackStack
Stack
 
Functions
FunctionsFunctions
Functions
 
Computer communication and networks
Computer communication and networks Computer communication and networks
Computer communication and networks
 

Kürzlich hochgeladen

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 

Kürzlich hochgeladen (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.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]; int chapter_no; public: void teaching(); //* member function *// }; Data members 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 ModeA 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 examplrclass sum { Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 2. Page 2 of 11 int a,b; void read(); public : int c; void add(); void disp(); }; sum ob; Private members by default Now let us see the following criteriaob.a; ob.b; ob.read(); ob.c; ob.add(); ob.disp(); All are invalid as private members can be access directly. All are valid as public members can be 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 MembersThe 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 examplevoid 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 exampleclass 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 ArgumentAs 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 functionAs 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 FunctionNormally 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 circumstancesa) 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 FunctiosIf 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 classWhen 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