0% found this document useful (0 votes)
20 views91 pages

Unit 1.2

The document provides an overview of classes in C++, detailing their definition, structure, and the concept of objects as instances of classes. It explains how to create and access class members, the role of member functions, and the use of access specifiers. Additionally, it covers static data members and functions, inline functions, and their advantages in reducing function call overhead.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views91 pages

Unit 1.2

The document provides an overview of classes in C++, detailing their definition, structure, and the concept of objects as instances of classes. It explains how to create and access class members, the role of member functions, and the use of access specifiers. Additionally, it covers static data members and functions, inline functions, and their advantages in reducing function call overhead.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

What

. A class is user defined


data type defined
in C+ using Why
+keyword class followed by A class in C++ is the
the name of class. block, that leads building to
The body of class is
defined Oriented programming. It is a
inside the curly user-defined data type, which
and terminated bracket
by a Object- and
holds its own data members
s
semicolon at the end. member functions, which can be
accessed and used by creating an
instance of that class.
CONTENT
S
• Specifying a class
• Creating Objects
• Accessing the class members

6
Class

• A class is user defined data type which consists of two sections, a private and a
protected section that holds data and a public section that holds the interface
operations.
• A class definition is a process of naming a class and data variables, and methods
or interface operations of the class.
• Once a class has been defined, we can create any number of objects belonging to
that class.
• A class is collection of objects of similar type.

Example-- If fruit has been defined as a class, then the


statement fruit mango;
will create an object mango belonging to the class fruit.
3
Specifying A Class

Class specification has two parts:


• Class declaration
• Class function definitions
• Class declaration describes type and scope of its members
•Class function definition describes how class functions are implemented.
Example:
class class_name
{ private: variable
declarations; public:
function declaration;
};
4
Simple Class Program---Program to enter and display the contents of a
class
#include<iostream.h>
#include<conio.h>
class emp
{
public:
int empid;
char name[15];
class data
{
public:

5
Program to enter and display the contents of a class

int day,month,year;
}doj;
}e;
void main()
{
clrscr();
cout<<"enter employee id"<<endl;
cin>>e.empid;
cout<<"enter name"<<endl;
cin>>e.name;

6
Program to enter and display the contents of a class

cout<<"enter date of joining"<<endl;


cin>>e.doj.day;
cout<<"enter month of
joining"<<endl;
cin>>e.doj.month;
cout<<"enter year of joining"<<endl;
cin>>e.doj.year;
cout<<"emp.id:"<<e.empid<<endl;
cout<<"emp name:"<<e.name<<endl;
cout<<"date of
joing:"<<e.doj.day<<"-"<<e.doj.mont
h<<"-"<<e.doj.year<<endl;
getch(); 7
Objects

• Oops uses object as fundamental Building Block Definitions.


• Objects are the basic run time entities in object oriented System.
• Every object is associated with Data and Functions which
define meaningful operations on an object.
• Object is a real world existing entity.
• Object is an instance of a particular class.

8
Creating Objects

• Objects are created from classes. Class objects are declared in a similar way as
variables are declared. The class name must start, followed by the object name.
For example,
ABC ob1,ob2; //object declaration will create two objects ob1 and
ob2 of ABC class type.
• Memory space is allocated separately to each object for their data members.
• Member variables store different values for different objects of a class.

9
Accessing Class Members

• Accessing a data member depends on the access control of that data


member. If its public, then the data member can be easily accessed
using the direct member access (.) operator with the object of that
class.
• If, the data member is defined as private or protected, then we
cannot access the data variables directly. Then we will have to create
special public member functions to access, use or initialize the private
and protected data members. These member functions are also
called Accessors and Mutator methods or getter and setter functions.

10
Accessing Class Members

class person { //class declaration


public: //access specifier
string name; //variable declaration
int number;
};
main() { //main function
person obj; //object creation for class
cout<<“Enter name:”; //get input values for object variables
cin>>obj.name;
cout<<“Enter number:”;
cin>>obj.number;
cout<<obj.name<<“:”<<obj.number<<endl;

11
Accessing Public Class Members(Example)

Following is an example to show you how to initialize and use the public data
members
using the dot (.) operator and the respective object of
class. class Student
{
public:
int rollno;
string name;
};
int main()
{ 12
Accessing Public Class Members

Student
A;
Student B;
// setting values for A
object A.rollno=2021;
A.name="Karan";
// setting values for B
object
B.rollno=20212121;
B.name="Arjun";
cout <<"Name and Roll no 17
OUTPUT:

Name and Roll no of A is: Karan-2021


Name and Roll no of B is: Arjun-
20212121

18
What
. A function declared as a
member of a class is called
as a member function. Why
Member functions are Member functions and functions
mostly given the attributes are
names used interchangeably in
of public because they reference classes. Function prototypes
have to be called outside are declared within the class definition.
the class either in a These prototypes can take the form of
non-class functions as well as class
program or in the function.
suitable prototypes. Functions can be
declared and defined within the class
definition.

5
CONTENT
S
• Defining a Member functions
inside and
outside class
• Access specifiers

20
Defining a Member function

There are two ways:


1. Member functions defined inside class
• Do not need scope resolution operator, class name.
2. Member functions defined outside class
• Using Binary scope resolution operator (::)
• “Ties” member name to class name
• Uniquely identify functions of particular class
• Different classes can have member functions with same name

Format for defining member functions outside the class is:


returnType ClassName::MemberFunctionName( )
{

}

17
Defining a Member function Inside class

We define the function inside class then we don't not need to declare it first, we can
directly define the function,the class name and the scope resolution operator are
not specified in the function header.Moreover, the member functions defined inside a class
definition are by default inline functions.

class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};
18
Defining a Member function Inside
class(Example) Contd…
class sample
{
private:
float x;
float
y;
public:
void
get()
{
cout<<"enter any two number"<<endl;
cin >>x>>y;
19
}
Defining a Member function Inside class(Example)
Contd…
void disp()
{
cout<<"First value = " <<x<<endl;
cout<<"Second value = "<<y<<endl;
cout<<"sum = "<<sum()<<endl;
cout<<"sub = "<<sub()<<endl;
cout<<"mul = "<<mul()<<endl;
cout<<"div = "<<div()<<endl;
}
float sum()
{
return(x+y);
} 24
Defining a Member function Inside class(Example)
Contd…
float sub()
{
return(x-y);
}
float mul()
{
return(x*y);
}
float div()
{
return (x/y);
}
}; 25
Defining a Member function Inside class(Example)
Contd…
void main()
{
clrscr();
sample temp;
temp.get();
temp.disp();
temp.sum();
temp.sub();
temp.mul();
temp.div();
getch();
} 26
Defining a Member function outside the class
But if we define the member function outside the class definition then we must declare
the function inside class definition and then define it outside.
The definition of member function outside the class differs from normal function
definition, as the function name in the function header is preceded by the class name and
the scope resolution operator (: :). The scope resolution operator informs the compiler
what class the member belongs to. The syntax for defining a member function outside the
class is

return_type class_name :: function_name (parameter_list)


{
// body of the member function
}
23
Defining a Member function outside the class

class Cube
{
public:
int side;
int getVolume();
} // member function defined outside class definition
int Cube :: getVolume()
{
return side*side*side;
}

24
Defining a Member function outside the class(Example)
Contd…
class sam
{
private:
float x;
float
y;
public:
void get();
void disp();
float sum();
float diff();
float mul();
float div();
25
}; //End of
Defining a Member function outside the class(Example)
Contd…
void sam::get()
{
cout<<"Enter any two numbers"<<endl;
cin>>x>>y;
}
void sam::disp()
{
cout<<"First value="<<x<<endl;
cout<<"Second value="<<y<<endl;
cout<<"Sum="<<sum()<<endl;

26
Defining a Member function outside the class(Example)
Contd…
cout<<"Diff="<<diff()<<endl;
cout<<"Mul="<<mul()<<endl;
cout<<"Div="<<div()<<endl;
}
float sam::sum()
{
return(x+y);
}
float sam::diff()
{
return(x-y);
}
27
Defining a Member function outside the class(Example)
Contd…

float sam::mul()
{
return(x*y);
}
float sam::div()
{
return(x/y);
}

28
Defining a Member function outside the class(Example)
Contd…
void main()
{
clrscr();
sam temp;
temp.get();
temp.disp(
);
temp.sum(
);
temp.diff();
temp.mul()
;
temp.div();
29
getch();
Access Specifiers

Private
• A member data can only be accessed by the member functions and friends of this
class.
• The member functions and friends of this class can always read or write private data
members.
• Private data members is not accessible to the outside world.
Public
• Can be accessed by any function in the outside world.
• Public implementation operations are also called member functions or methods or
interfaces to out of the class.
Protected
• Members can only be accessed by member functions and friends of this class.
• Not accessible to the outside world
30
Access Specifiers
PUBLIC PRIVATE PROTECTED
• Data members and • No one can access the • Makes class member
member class members declared inaccessible outside the
functions declared public private outside that class. class.
can be accessed by other
classes too • Compile time error • But they can be accessed
by any subclass of that
class.
• class PublicAccess { • class PrivateAccess { • class ProtectedAccess {
• public: • private: • protected:
• int x; // int x; • int x;
Data // Data // Data
Member Member Member
Declaration Declaration Declaration
• void display(); • void display(); • void display();
// Member // Member • //
Function decaration Function Member
• } decaration Function decaration
•} •} 19
What
Static data members
class members that are
are
declared using Why
the static keyword. There A typical use of static members is for
is only one copy of recording data common to all objects of
the static data member in a class. For example, you can use a static
the class, even if there are data member as a counter to store the
many class objects number of objects of a particular class
type that are created.
CONTENT
S
• Static data members
• Static member functions

37
Static Data members

Used to store value common to the whole class. The static data
member differs from an ordinary data member in the following
ways :
(i)Only a single copy of the static data member is used by all the
objects.
(ii) It can be used within the class but its lifetime is the whole
program.

For making a data member static, we require :


(a) Declare it within the class.
(b) Define it outside the class. 34
Static data members

Class Student
{
Static int count; //declaration within class
-
};
The static data member is defined outside the class as :
int student :: count; //definition outside class
We can also initialize the static data member at the time of its definition
as:
int student :: count = 0;
If we define three objects as : student obj1, obj2, obj3;
35
Displaying Static data members
#include<iostream>
using namespace std;
class date
{
public:int day;
int month;
int year;

};
int main()
{
class date d;
d.day=21;
d.month=1;
d.year=2013;
cout<<"Today's date = "<<d.day<<"/"<<d.month<<"/"<<d.year<<endl;
return 0;
40
}
Static Data members(Example)

#include <iostream>
using namespace std;
void Test(){
static int x = 1;
x = ++x;
int y = 1;
y = ++y;
cout<<"x =
"<<x<<"n"; cout<<"y
= "<<y<<"n";
}
37
Static Data members(Example)

int main()
{
Test();
Test();
return 0;
}
Output:

38
Static member function

A static member function can access only the static members of a class.
In C++, a static member function differs from the other member functions in
the following ways:
(i)Only static members (functions or variables) of the same class can be accessed
by a static member function.
(ii)It is called by using the name of the class rather than an object as
given below:
Name_of_the_class :: function_name
For example:
student::showcount();

39
Static member function
To create a static member function we need to use the static keyword while
declaring the function. Since static member variables are class properties and not
object properties, to access them we need to use the class name instead of the object
name
Properties of static member functions:
• A static function can only access other static variables or functions present in
the same class
• Static member functions are called using the class name.
class_name::function_name( )

40
Static member function(example)
class Demo
{
private:static int X;
public:static void fun()
{
cout <<"Value of X: " << X << endl;
}
}; int Demo :: X =10;
int main()
{Demo X;
X.fun();
return
0;
41
Static member function(Example)

• class
Example{ static
int Number; int n;
public:
void set_n(){
n = ++Number;
}
void show_n(){
cout<<"value
of n =
"<<n<<endl;
42
}
Static member function(Example)

cout<<"value of Number = "<<Number<<endl;


}
};
int Example:: Number;
int main()
{
Example example1,
example2; example1.set_n();
example2.set_n();

43
Static member function

example1.show_n();
example2.show_n();
Example::show_Number();
return 0;
}
Output:

44
CONTENT
S
• Introduction
to Inline
Function
• Advantages
of inline
function
• Examples

49
INLINE
FUNCTION
Inline functions are actual functions, which are copied everywhere
during compilation,
like preprocessor macro, so the overhead of function calling is
reduced. All the
functions defined inside class definition are by default inline, but
you can also make any non-class function inline by using keyword
inline with them.
An inline function is expanded (i.e. the function code is replaced when a call
to the inline function is made) in the line where it is invoked.
Syntax:
inline function_header
{
body of the function
} 46
INLINE FUNCTION
• We must keep inline functions small, small inline
functions have better efficiency.
• Inline functions do increase efficiency, but we should not make
all the functions inline. Because if we make large functions
inline, it may lead to code bloat, and might affect the
speed too.
• Hence, it is adviced to define large functions outside the
class definition using scope resolution :: operator, because if
we define such functions inside class definition, then they
become inline automatically.
• Inline functions are kept in the Symbol Table by the compiler,
and all the call for such functions is taken care at compile
time 47
INLINE
FUNCTION
The inlining does not work for the following situations :
1.For functions returning values and having a loop or a
switch or a goto statement.
2.For functions that do not return value and having a
return statement.
3.For functions having static variable(s).
4.If the inline functions are recursive (i.e. a function
defined in terms of itself).

48
Inline functions provide following
advantages:
1) Function call overhead doesn’t occur.
2)It also saves the overhead of push/pop variables on
the stack when function is called.
3) It also saves overhead of a return call from a function.
4)When you inline a function, you may enable compiler
to perform context specific optimization on the body of
function. Such optimizations are not possible for
normal function calls. Other optimizations can be
obtained by considering the flows of calling context
49
and the called context.
Exampl
e
#include<iostream>
using namespace
inline int std;
Add(int x,int y)
{

return x+y;
}

int main()
{

cout<<"\n\tThe Sum is : " << Add(10,20);


cout<<"\n\tThe Sum is : " <<
Add(45,83); cout<<"\n\tThe Sum is : "
} << Add(27,48); 54
Outpu
t:

51
INLINE
FUNCTION
• It is also possible to define the inline function inside the class. In fact,
all the functions defined inside the class are implicitly inline. Thus, all
the restrictions of inline functions are also applied here.
• If you need to explicitly declare inline function in the class then just
declare the function inside the class and define it outside the class
using inline keyword.

52
Exam
ple
#include <iostream>
using namespace std;
class operation
{
int a, b, add, sub;

public:
void get();
void sum();
void difference();

};
inline void operation :: get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
} 57
Example
Contd…
inline void operation :: sum()
{
add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
}

inline void operation :: difference()


{
sub = a-b;
cout << "Difference of two numbers: " << a-b << "\n";
}

54
Example
Contd…
int main()
{
cout << "Program using inline function\n";
operation s;
s.get();
s.sum();
s.difference()
;
return 0;
}

55
Outp
ut

56
CONTENT
S
• Concept of how to pass and
return the objects
to function
• Syntax
• Examples

61
PASSING OBJECT AS FUNCTION
ARGUMENTS
In C++ we can pass class’s objects as arguments and also
return them from a function the same way we pass and return
other variables. No special keyword or header file is required
to do so.
Passing an Object as argument
To pass an object as an argument we write the object name
as the argument while calling the function the same way
we do it for other variables.
The objects of a class can be passed as arguments to member
functions as well as nonmember functions either by value or
by reference.
62
Exam
ple
#include<iostream>
using namespace std;
class A {
public:
int n=100;
char ch='A';
void disp(A a)
{cout<<a.n<
<endl;
cout<<a.ch
<<endl;
}
};
int main()
{
A obj;
obj.disp(obj);
OUTP
UT
Example: C++ program to add two
complex number by passing objects as
function
#include<iostream> arguments (By value)
using namespace std;

class complex
{
int re, im;
public:
void
get()
{
co
ut
<<
"\
nE
nt
Example
Contd…
void disp()
{
cout<<re<<"+"<<im<<"i"<<"\n";

}
void sum(complex,complex);
};

void complex::sum(complex c1,complex c2)


{
re=c1.re+c2.re;
im=c1.im+c2.im;
}
Example
Contd…
int main()
{
complex c1,c2,c3;
cout<<"Enter 1st complex no.: \n";
c1.get();
cout<<"\nEnter 2nd complex no.: \n";
c2.get();
cout<<"\nThe 1st complex no. is :: ";
c1.disp();
cout<<"\nThe 2nd complex no. is :: ";
c2.disp();
c3.sum(c1,c2);
cout<<"\nThe Sum of two complex
no.s are :: ";
c3.disp();
return 0; }
Outp
ut
Example: C++ program to add two
complex number by passing objects as
function arguments(By Reference)
#include <iostream>
using namespace std;

class Complex
{
public:
int real;
int imag;
public:

void
readDa
ta()
{
cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
Example
Contd…
void addComplexNumbers(Complex &comp1)
{
// real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
real=comp1.real+real;
comp1.real++;

// imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
imag=comp1.imag+imag;
}

void displaySum()
{
cout << "Sum = " << real<< "+" << imag << "i";
}
};
Example
Contd…
int main()
{
Complex c1,c2,c3;
c1.readData();
c2.readData();

c2.addComplexNumbers(c1);
c2.displaySum();
cout<<c1.real;
return 0;
}
Outp
ut
Return object from a
function
The syntax for defining a function that returns an object by value is
class_name function_name (parameter_list)
{
// body of the function
}
Return object from a
function
Exam
ple
#include <iostream>
using namespace std;
class Student {
public:
double marks1,
marks2;
};

// function that returns object of Student


Student createStudent() {
Student student;

// Initialize member variables of


Student
student.marks1 = 96.5;
student.marks2 = 75.0;
Example
Contd…
// print member variables of Student
cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;

return student;
}

int main() {
Student student1;
// Call function
student1 = createStudent();
return 0;
}
Outp
ut
Explanati
on
CONTENT
S
• Concept of Friend Function
• Characteristics of friend
Function
• Examples to Understand the
concept of Friend
Function

80
Friend
Function
If a function is defined as a friend function in C++, then the protected
and private data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a
friend function.
For accessing the data, the declaration of a friend function should be
done inside the body of a class starting with the keyword friend.

81
Friend
Function
Declaration of friend function in C++
class class_name
{
friend data_type function_name(argument/s); // syntax of
friend function.
};
In the above declaration, the friend function is preceded by the
keyword friend. The function can be defined anywhere in the program
like a normal C++ function. The function definition does not use either
the keyword friend or scope resolution operator.
Characteristics of a Friend
function
•The function is not in the scope of the class to which it has been
declared as a friend.
•It cannot be called using the object as it is not in the scope of that
class.
•It can be invoked like a normal function without using the object.
•It cannot access the member names directly and has to use an object
name and dot membership operator with the member name.
•It can be declared either in the private or the public part.
Exam
ple
#include <iostream>

using namespace std;

class Temperature
{
int celsius;
public:
Temperature(
)
{
celsius = 0;
} // declaring friend function
friend int
temp( Temper
Example
Contd…
int temp( Temperature t ) // friend function definition
{
t.celsius = 40;
return t.celsius;
}

int main()
{
Temperature tm;
cout << "Temperature in celsius : " << temp( tm ) << endl;
return 0;
}
OUTP
UT
Example: Addition of two numbers
using friend function
#include<iostream.h
> #include<conio.h>
using namespace std;
class temp
{
int a, b, add;
public:
void input()
{
cout << "Enter the
value of x and y:";
}cin >> x>>y;
Example
friend void add(temp &t);
Contd…
void display()
{
cout << "The sum is :" << z;
}
};
void add(temp &t)
{
t.add = t.a + t.b;
}
Example
Contd…
int main()
{
temp t1;
t1.input();
add(t1);
t1.display
();
return 0;
}
Outp
ut
Example: Program to add two
complex numbers using
friend function
#include<iostream>
using namespace std;
class complex
{ int real,imag;
public:
void set()
{cout<<"enter real
and imag part";
cin>>real>>imag;
}
friend complex
sum(complex,comple
x);
Example
Contd…
void complex::display()
{
cout<<"the sum of complex num is"<<real<<"+i"<<imag;
}
complex sum(complex a,complex b)
{
complex t;
t.real=a.real+b.real;
t.imag=a.imag+b.imag;
return t;
}
Example
Contd…
int main()

{
complex a,b,c;
a.set();
b.set();
c=sum(a,b);
c.display();

return(0);
}
Outp
ut
Summary

In this lecture we have We have discussed about how


discussed about Class. to specify a class.

Discussed about how to create Discussed about Accessing


Objects. Class members.

95

You might also like