CLASSES AND OBJECTS
Structure overview
• A structure is collection of simple variable, the variable in
a structure can be of different type.
• Ex:
struct student{
int roll_no;
char name[20];
float marks;
};
• C++ support all features of structure in c, but c++
attempts to bring user-defined types as close as possible
the built-in data type and also provide a facility to hide
data.
C++ Lecture note by hansa halai
Difference Between Structure and
Class in C++
• In C++, a structure works the same way as a
class, except for just two small differences. The
most important of them is hiding
implementation details. A structure will by
default not hide its implementation details from
whoever uses it in code, while a class by default
hides all its implementation details and will
therefore by default prevent the programmer
from accessing them. The following table
summarizes all of the fundamental differences.
C++ Lecture note by
hansa halai
Class Structure
1. Members of a class are private by
default.
1. Members of a structure are public
by default.
2. An instance of a class is called an
‘object’.
2. An instance of structure is called the
‘structure variable’.
3. Member classes/structures of a
class are private by default but not all
programming languages have this
default behavior eg Java etc.
3. Member classes/structures of a
structure are public by default.
C++ Lecture i
It is declared using
the class keyword.
4. It is declared using
the struct keyword.
5. It is normally used for
data abstraction and further
inheritance.
5. It is normally used for the
grouping of data
6. NULL values are possible
in Class.
6. NULL values are not possible.
7. Syntax:
class class_name{
data_member;
member_function;
};
7. Syntax:
struct structure_name{
type structure_member1;
type structure_member2;
};
C++ Lecture
Class
• A class is a way to bind data and associated function together.
• A class is an expanded concept of a data structure, instead of
holding only data , it can hold both data and function.
• The data is to be hidden from external use.
• Classes are generally declared using the keyword class, with
the following format:
class class_name
{
private:
variable declaration;
public:
function declaration;
…
};
C++ Lecture note by hansa halai
• The body of the declaration can contain members that can
be either data or function declaration, and optionally
access specifier.
• The variable declared inside the class is known as data
member and function are known as member
functions.
• Access specifier are keyword in object oriented language
that set the accessibility of classes, method and other
member.
• Access specifier is one of the following keyword: public,
private, protected.
C++ Lecture note by hansa halai
• These specifier modify the access rights that the member following
them acquire:
 private members of class are accessible only from within other
member of same class or from their friends.
 protected members are accessible form members of their
same class and from their friends but also from members of their
derived classes.
 public members are accessible from anywhere the object is
visible.
• Only member function can have access to private data member and
private function of that data.
C++ Lecture note by hansa halai
• #include <iostream>
• class Addition {
• private:
• int num1, num2, sum;
• public:
• void input() {
• cout << "Enter two numbers: ";
• cin >> num1 >> num2;
• }
• void calculate() {
• sum = num1 + num2;
• }
• void output() {
• cout << "The sum of " << num1 << " and " << num2 << " is " << sum << std::endl;
• }
• };
•
• int main() {
• Addition add;
• add.input();
• add.calculate();
• add.output();
• return 0;
C++ Lecture note
Object
• Once a class has been created, we can create variable of
that type(class type) by using following syntax which is
called object.
• Syntax:
class_name variable_name;
Ex:
student s;
• we can create any number of objects belonging to that
class by declaring more than one object in one statement.
This statement are written in main().
• The objects can also be defined by placing their name
immediately after the closing brace of the class.
C++ Lecture note by hansa halai
• Syntax:
class class_name
{
….
}object1,object2,…;
• Ex:
class student
{
…
}s1,s2;
C++ Lecture note by hansa halai
• Accessing class member:
A object can be declared in the main(),and member
functions are declared in class in public section so always a
member function can be called by using object.
• Syntax:
object_name.member_function(arguments);
Ex:
s.getdata();
• A data member can also be access by using object only , if
data member is declared as public.
• If data member is declared private then you can not access
it by using object directly in object.
C++ Lecture note by hansa halai
Defining member function
• A member function can be defined in two places in the class:
1. inside the class definition
2. outside the class definition
1) Inside the class definition:
To write a member function inside the class instead of only
declaration(prototype).
Ex:
class item
{
int num;
float cost;
C++ Lecture note by hansa halai
public:
void getdata(int a,float b)
void putdata(void)
{
cout<<number;
cout<<cost;
}
};
….
C++ Lecture note by hansa halai
void (C++)
C++ Lecture note by
hansa halai
When used as a function return type, the void
keyword specifies that the function doesn't
return a value.
 when used for a function’s parameter list, void
specifies that the function takes no parameters.
When used in the declaration of a pointer, void
specifies that the pointer is universal.
the void keyword specifies that the function doesn't return a value.
the void keyword specifies that the function doesn't return a value.
When used for a function's parameter list, void specifies that the
2) Outside the class definition:
• To write function we need to declare function inside
the class and definition(function body) is written
outside the class.
• The general form of a member function definition:
return_type class_name::function_name(arument)
{
function body
}
• The membership label class_name :: tells the
compiler that the function function_Name belongs
to the class class_name.
• :: is scope resolution operator.
C++ Lecture note by hansa halai
USE of scope resolution operator
• // C++ program to show that we can access a global variable
• // using scope resolution operator :: when there is a local
• // variable with same name
• #include<iostream>
• using namespace std;
• int x; // Global x
• int main()
• {
• int x = 10; // Local x
• cout << "Value of global x is " << ::x;
• cout << "nValue of local x is " << x;
• return 0;
• }
C++ Lecture note by
hansa halai
Ex:
….
void item::getdata(int a, float b)
{
number=a;
coat=b;
}
void item::putdata(void)
{
cout<<“number “<<number;
cout<< “cost ”<<cost;
}
…
C++ Lecture note by hansa halai
• // C++ program to demonstrate function
• // declaration outside class
• #include <iostream>
• using namespace std;
• class Geeks
• {
• public:
• string geekname;
• int id;
• void printname();
•
• // printid is defined inside class definition
• void printid()
• {
• cout <<"Geek id is: "<<id;
• }
• };
• // Definition of printname using scope resolution operator ::
• void Geeks::printname()
• {
• cout <<"Geekname is: "<<geekname;
• }
C++ Lecture note by
hansa halai
• int main() {
•
• Geeks obj1;
• obj1.geekname = "xyz";
• obj1.id=15;
•
• // call printname()
• obj1.printname();
• cout << endl;
•
• // call printid()
• obj1.printid();
• return 0;
• }
C++ Lecture note by
hansa halai
INLINE FUNCTION
• A function is used to write code redundancy, as
well as to save memory space, when a function is
invoked a bunch of task is performed ex
matching arguments, matching return type
passing control from calling to definition and
vice-versa.
• If our function body is small than it is a time
consuming process therefore C++ introduced
concept of inline function
C++ Lecture note by
hansa halai
CONT..
• C++ provides inline functions to reduce the function call
overhead. An inline function is a function that is
expanded in line when it is called. When the inline
function is called whole code of the inline function gets
inserted or substituted at the point of the inline function
call. This substitution is performed by the C++ compiler
at compile time. An inline function may increase
efficiency if it is small.
C++ Lecture note by
hansa halai
Syntax:
C++ Lecture note by
hansa halai
inline return-type functionname
(parameters)
{ // function code }
C++ Lecture note by
hansa halai
The compiler may not perform
inlinie in such circumstances as:
• If a function contains a loop. (for, while and do-
while)
• If a function contains static variables.
• If a function is recursive.
• If a function return type is other than void, and
the return statement doesn’t exist in a function
body.
• If a function contains a switch or goto
statement.
C++ Lecture note by
hansa halai
Why Inline Functions are Used?
• When the program executes the function call instruction the CPU
stores the memory address of the instruction following the function
call, copies the arguments of the function on the stack, and finally
transfers control to the specified function. The CPU then executes
the function code, stores the function return value in a predefined
memory location/register, and returns control to the calling
function. This can become overhead if the execution time of the
function is less than the switching time from the caller function to
called function
• For functions that are large and/or perform complex tasks, the
overhead of the function call is usually insignificant compared to the
amount of time the function takes to run. However, for small,
commonly-used functions, the time needed to make the function
call is often a lot more than the time needed to actually execute the
function’s code. This overhead occurs for small functions because
the execution time of a small function is less than the switching
time.
C++ Lecture note by
hansa halai
Making an outside function inline
• We can define a member function outside and still make it
inline by just using the qualifier inline in the header line of
function definition.
• Ex:
class item
{
int number;
Float cost;
public:
void getdata(int a, float b);
};
inline void item :: getdata(int a,float b)
{
number = a;
cost = b;
}
C++ Lecture note by hansa halai
• #include <iostream>
• using namespace std;
• inline int fun(int a, int b)
• {
• return a+b;
• }
• main()
• {
• int value=fun(34,67);
• Cout<<value;
• }
C++ Lecture note by
hansa halai
Nesting Member Function
• A member function can be called by using its name inside another
member function the same class is called nesting member
function.
• Ex:
#include<iostream>
using namespace std;
class number
{
private:
int a,b,s1,s2;
public:
int getdata(int m,int n);
int sum();
int sub();
C++ Lecture note by hansa halai
C++ Lecture note by hansa halai
int show()
{
cout<<"n Enter number1: ";
cin>>a;
cout<<"n Enter number2: ";
cin>>b;
cout<<"n Answer of Addition:"<<sum()<<endl;
cout<<"n Answer of Addition:"<<sub()<<endl;
}
};
int number::getdata(int m,int n)
{
a=m;
b=n;
}
C++ Lecture note by hansa halai
int number::sum()
{
s1=a+b;
return(s1);
}
int number :: sub()
{
s2=a-b;
return(s2);
}
int main()
{
number x;
x.getdata(10,20);
x.show();
return 0;
}
Private Member Function
• Generally we declare , data members are in private section
and member function in public section, that’s why we call
a member function from main() through object.
• But if we declare a member function in private section
then we can not call directly from the main(), because it’s
private function.
• To call private function , we have to create public function
of that class and we call this private function inside that
public function , then the public function called by object
from main().
C++ Lecture note by hansa halai
C++ Lecture note by hansa halai
Ex:
#include<iostream>
using namespace std;
class value
{
private:
int a,b;
void getdata();
public:
void show();
};
void value::getdata()
{
cout<<"Enter number1: ";
cin>>a;
cout<<"Enter number2: ";
cin>>b;
}
C++ Lecture note by hansa halai
void value::show()
{
getdata();
cout<<"Two numbers are "<<a <<"n"<<b;
}
int main()
{
value v;
v.show();
return 0;
}
Array within class:
• The arrays can be used as member variable in a class.
• An array is collection of same data type or group of data
item that store in a common name.
• Syntax:
data_type name[size]={list of value};
Like
int number[4]={1,2,3,4};
C++ Lecture note by hansa halai
Ex:
C++ Lecture note by hansa halai
#include<iostream>
using namespace std;
class average
{
private:
int n,A[20];
public:
void getdata()
{
cout<<"Number of element: ";
cin>>n;
cout<<"Enter the data in array:n ";
for(int i=0;i<n;i++)
{
cout<<"A["<<i<<"]";
cin>>A[i];
}
}
C++ Lecture note by hansa halai
float avg()
{
float sum=0,ans;
for(int i=0;i<n;i++)
sum=sum+A[i];
ans=sum/n;
cout<<"Average is: "<<ans;
}
};
int main()
{
average a;
a.getdata();
a.avg();
return 0;
}
Memory allocation for object
• The memory space for objects are allocated when they are
declared , not when the class is specified.
• For member function , when member function are created
, it will occupy the memory space only once when they are
defining in a class.
• So all objects created for that class can use same member
functions , so no separate space is allocated for member
functions when the object are created.
• For data member , only space for data members is
allocated separately for each object when is created.
C++ Lecture note by hansa halai
• The separate space allocation for data member is essential
because the data member will hold different data values for
different objects.
• For example, a class student have three data members such
as reg_no, age, per and two member functions
getdata() and show().
• If we create three object S1 ,S2, S3 then,
object S1 takes up space for: reg_no , age , per
object S2 takes up space for: reg_no , age , per
object S3 takes up space for: reg_no , age , per
But it will access common member function getdata()
and show(), so it will take up space only one time when
class is created.
C++ Lecture note by hansa halai
Constructor
• Constructor in C++ is a special method that is invoked automatically at
the time of object creation. It is used to initialize the data members of new
objects generally. The constructor in C++ has the same name as the class or
structure. It constructs the values i.e. provides data for the object which is
why it is known as a constructor.
• Constructor is a member function of a class, whose name is the same as the
class name.
• Constructor is a special type of member function that is used to initialize the
data members for an object of a class automatically when an object of the
same class is created.
• Constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as a
constructor.
• Constructors do not return value, hence they do not have a return type.
• A constructor gets called automatically when we create the object of the
class
C++ Lecture note by
hansa halai
Syntax for Defining the Constructor
Within the Class
C++ Lecture note by
hansa halai
<class-name> (list-of-parameters)
{
// constructor definition
}
Syntax for Defining the Constructor
Outside the Class
C++ Lecture note by
hansa halai
<class-name>: :<class-name>(list-of-parameters)
{
// constructor definition
}
C++ Lecture note by
hansa halai
#include <iostream>
• using namespace std;
• class student {
• int rno;
• char name[50];
• double fee;
• public:
• // constructor
• student()
• {
• cout << "Enter the RollNo:";
• cin >> rno;
• cout << "Enter the Name:";
• cin >> name;
• cout << "Enter the Fee:";
• cin >> fee;
• }
• void display()
• {
• cout << endl << rno << "t" << name << "t" << fee;
• }
• };
• int main()
• {
• student s; // constructor gets called
automatically when
• // we create the object of the
class
• s.display();
• return 0;
• }
C++ Lecture note by
hansa halai
C++ Lecture note by
hansa halai
• // defining the constructor outside the class
• #include <iostream>
• using namespace std;
• class student {
• int rno;
• char name[50];
• double fee;
• public:
• // constructor declaration only
• student();
• void display();
• };
• // outside definition of constructor
• student::student()
• {
• cout << "Enter the RollNo:";
• cin >> rno;
• cout << "Enter the Name:";
• cin >> name;
• cout << "Enter the Fee:";
• cin >> fee;
• }
• void student::display()
• {
• cout << endl << rno << "t" << name << "t" << fee;
• }
• // driver code
• int main()
• {
• student s;
• s.display();
• return 0;
• }
C++ Lecture note by
hansa halai
Static data member
• Static variable are normally used to maintain values
common to the entire class.
• For example, a static data member can be used as a
counter that record occurrences of all the objects.
• A static member variable has certain characteristic:
1. It automatically initialized zero when the first object is
created , no other initialization is permitted. Where a
simple variable have initially garbage value.
2. Only one copy of that member is created for entire class
and shared by all objects of that class, no matter how
many objects are created.
3. It is visible only within a class, but its life time is the
entire program.
C++ Lecture note by hansa halai
• Static data members are class members that are
declared using static keywords.
• It is initialized before any object of this class is
created, even before the main starts.
C++ Lecture note by
hansa halai
C++ Lecture note by
hansa halai
• #include <iostream>
• #include <string.h>
• using namespace std;
• // create class of the Car
• class Car
• {
• private:
• int car_id;
• char car_name[20];
• int marks;
C++ Lecture note by
hansa halai
• public:
• // declare a static data member
• static int static_member;
• Car()
• {
• static_member++;
• }
• void inp()
• {
• cout << " nn Enter the Id of the Car: " << endl;
• cin >> car_id; // input the id
• cout << " Enter the name of the Car: " << endl;
• cin >> car_name;
• cout << " Number of the Marks (1 -
10): " << endl;
• cin >> marks;
• }
C++ Lecture note by
hansa halai
• // display the entered details
• void disp ()
• {
• cout << " n Id of the Car: " << car_id;
• cout << "n Name of the Car: " << car_name;
• cout << " n Marks: " << marks;
•
• }
• };
C++ Lecture note by
hansa halai
• // initialized the static data member to 0
• int Car::static_member = 0;
• int main ()
• {
• // create object for the class Car
• Car c1;
• // call inp() function to insert values
• c1. inp ();
• c1. disp();
•
• //create another object
• Car c2;
• // call inp() function to insert values
• c2. inp ();
• c2. disp();
• cout << " n No. of objects created in the class: " << Car :: static_m
ember <<endl;
• return 0;
• }
C++ Lecture note by
hansa halai
Static member function:
• A member function that is declared static has the
following properties:
 A static function can have access to only other static
members(function or variable) declared in the same class.
 A static member function can be called using the class
name.
like, class_name :: Function_name();
test :: getdata();
C++ Lecture note by hansa halai
Ex:
C++ Lecture note by hansa halai
#include<iostream>
using namespace std;
class stat_fun
{
int obj;
static int count;
public:
void stat()
{
obj=++count;
}
void showObject()
{
cout<<"n object number is: "<<obj;
}
static void showcount()
{
cout<<"ncount object is:"<<count;
}
};
C++ Lecture note by hansa halai
int stat_fun::count;
int main()
{
stat_fun o1,o2;
o1.stat();
o1.stat();
stat_fun::showcount();
stat_fun o3;
o3.stat();
stat_fun::showcount();
return 0;
}
Arrays of object:
• As an array can be of any data type including struct. Similarly,
we can also have arrays of variable that are of the type class.
Such variables are called array of objects.
• For example:
class student {
private: float per;
public: int regno,age;
void getdata();
void show();
};
For this class if we required 100 student , then we are not
declare different s1,s2,…,s100 object because it’s very critical
task. For this problem we use array of object.
C++ Lecture note by hansa halai
Ex:
C++ Lecture note by hansa halai
#include<iostream>
using namespace std;
class student{
char name[15];
float age;
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<"Enter Name: ";
cin>>name;
cout<<"Enter Age: ";
cin>>age;
}
void student :: putdata()
{
cout<<"Name: "<<name<<"n";
cout<<"Age: "<<age <<"n";
}
C++ Lecture note by hansa halai
const int size=2;
int main()
{
student s[size]; // array of object
for(int i=0;i<size;i++)
{
cout<<"Detail of student"<<i+1<<"n";
s[i].getdata();
}
cout<<"n";
for(int i=0;i<size;i++)
{
cout<<"nnStudent"<<i+1<<"n";
cout<<"--------n";
s[i].putdata();
}
return 0;
}
Object as function argument:
• Like any other data type, an object may be used as a
function argument. This can be done in two way:
1. A copy of the entire object is passed to the function,
which is called call by value.
2. Only the address of the object is transferred to the
function, which is called call/pass by reference.
C++ Lecture note by hansa halai
EX:
C++ Lecture note by hansa halai
#include<iostream>
using namespace std;
class Square{
int x;
public:
void getdata(int m)
{
x=m;
}
int answer(Square s)
{
x=s.x*s.x;
}
void show()
{
cout<<"Answer is:"<<x;
}
};
C++ Lecture note by hansa halai
int main()
{
Square s1,s2;
s1.getdata(6);
s2.answer(s1);
s2.show();
return 0;
}
Returning objects:
• A function can not only receive objects as
arguments but also can return them.
• Like:
C++ Lecture note by hansa halai
#include<iostream>
using namespace std;
class SUM
{
int x;
public:
void getdata(int m)
{
x=m;
}
C++ Lecture note by hansa halai
SUM sum(SUM s)
{
SUM temp;
temp.x=x+s.x;
return(temp);
}
void show()
{
cout<<"Answer is: "<<x;
}
};
int main()
{
SUM s1 ,s2,s3;
s1.getdata(4);
s2.getdata(10);
s3=s1.sum(s2);
s3.show();
return 0;
}
Friendly functions:
• Due to ‘data hiding ’ feature of c++, the private data
members of class can not be access outside the class. So a
function which are not member of the class, they can not
be access the private data of that class.
• In c++, there is facility available to access private data of
class even if it is not member function of that class. It is
possible bye using friend function.
• As the name suggests, the function acts as a friend to a
class. As a friend of a class, it can access its private and
protected members.
C++ Lecture note by hansa halai
• To make an outside function “friendly” to class, declare the
function as friend of that class.
• The friend functions are declared by using friend keyword.
• Syntax:
friend return_type function_name(arg_list);
• Generally arguments in friend functions are object type.
because of outside the class a data member can not directly
access, so a object can access it.
• A function can be declared as friend for any number of class.
It can not be member function of any class. It have full rights
to access private data of the class.
C++ Lecture note by hansa halai
• Advantage of having friend function:
1. We can able to access the other class members in our
class, if we use friend keyword.
2. We can access the members without inheriting the
class.
• Disadvantage:
1. Maximum size of memory will occupied by object
according to the size of friend member.
2. Break the concept of ‘data hiding’ in oop.
C++ Lecture note by hansa halai
• Characteristic of friend function:
1. It is not in the scope of the class which it has been
declared as friend.
2. It can not be called using the object of that class. It can
be invoked like a normal function without the help of
object.
3. It can not access data member directly, it must be use
object with dot(.) operator and data member.
4. Normally it has object as argument.
C++ Lecture note by hansa halai
Ex:
C++ Lecture note by hansa halai
#include<iostream>
using namespace std;
class MEAN{
int n1,n2;
public:
void getdata()
{
cout<<"Enter num1: ";
cin>>n1;
cout<<"Enter num2: ";
cin>>n2;
}
friend float ans(MEAN m);
};
C++ Lecture note by hansa halai
float ans(MEAN m)
{
return float(m.n1+m.n2)/2;
}
int main()
{
MEAN m1;
m1.getdata();
cout<<"Answer is: "<<ans(m1);
return 0;
}
Const member function:
• Function member can made constant by writing word
const keyword between header of the function and
body.
• Constant member function means it can not modify the
object.
• normally function member which are not supposed to
modify the object should be made constant so that there
are no chance that accidently function member modifies
the object.
• void mul(int , int) const; // constant function
{
Body statement..
}
C++ Lecture note by hansa halai
Pointer to member:
• Just like pointer to normal variable and function , we can
have pointer to class member function and member
variable.
• Syntax for declare pointer data member:
data_type class_name::*pointer_name;
• Ex
int A ::* p;
• You can initialize p like this also:
• syntax:
data_type class_name::*pointer_name=&class_name::data_member
• Ex:
int A::*p=&A::m;
C++ Lecture note by hansa halai
• Likewise, you can access the data member through a
pointer to a class.
• Ex:
A *p1 =new A;
int n =p1->*p; // assign to n the value of p1->m
p1->*p=5; // assign the value of 5 to p1->m
• Pointer to member functions are one of the c++’s
rarely used features, while they do not have widely
applicability, some time member function pointer are
useful to solve certain problems.
• Member function pointer can not be dereferenced directly
by themselves .they must be called on behalf of some
object.
C++ Lecture note by hansa halai
• To declare a pointer to member function you give the
prototype of function it can point to,as before but the name
of this function is replaced by a construction that scopes the
pointer – you give it the name of the class whose member
function it can point to.
• Syntax:
return_type (class_name::*pointer_name)(argument_list)
• You dereference a member function pointer by using .* or
->*, supplying a reference or pointer to an object on the left,
as appropriate , and the function pointer on the right.
• Note that member function does not have the same data type
as nonmember function that has the same number and type
of argument and the same return type.
C++ Lecture note by hansa halai
Ex:
#include<iostream>
using namespace std;
class test{
public:
int a;
void fun(int b)
{
cout<<"The value of b is: "<<b<<endl;
}
};
int main()
{
int test::*p=&test::a; // pointer to data member declaration
C++ Lecture note by hansa halai
void(test::*p1)(int)=&test::fun; // pointer to function declaration
test T;
T.*p=10;
cout<<"The value of a is:"<<T.*p<<endl;
(T.*p1)(20);
}
C++ Lecture note by hansa halai
UNIT3 on object oriented programming.pptx

UNIT3 on object oriented programming.pptx

  • 1.
  • 2.
    Structure overview • Astructure is collection of simple variable, the variable in a structure can be of different type. • Ex: struct student{ int roll_no; char name[20]; float marks; }; • C++ support all features of structure in c, but c++ attempts to bring user-defined types as close as possible the built-in data type and also provide a facility to hide data. C++ Lecture note by hansa halai
  • 3.
    Difference Between Structureand Class in C++ • In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whoever uses it in code, while a class by default hides all its implementation details and will therefore by default prevent the programmer from accessing them. The following table summarizes all of the fundamental differences. C++ Lecture note by hansa halai
  • 4.
    Class Structure 1. Membersof a class are private by default. 1. Members of a structure are public by default. 2. An instance of a class is called an ‘object’. 2. An instance of structure is called the ‘structure variable’. 3. Member classes/structures of a class are private by default but not all programming languages have this default behavior eg Java etc. 3. Member classes/structures of a structure are public by default. C++ Lecture i
  • 5.
    It is declaredusing the class keyword. 4. It is declared using the struct keyword. 5. It is normally used for data abstraction and further inheritance. 5. It is normally used for the grouping of data 6. NULL values are possible in Class. 6. NULL values are not possible. 7. Syntax: class class_name{ data_member; member_function; }; 7. Syntax: struct structure_name{ type structure_member1; type structure_member2; }; C++ Lecture
  • 6.
    Class • A classis a way to bind data and associated function together. • A class is an expanded concept of a data structure, instead of holding only data , it can hold both data and function. • The data is to be hidden from external use. • Classes are generally declared using the keyword class, with the following format: class class_name { private: variable declaration; public: function declaration; … }; C++ Lecture note by hansa halai
  • 7.
    • The bodyof the declaration can contain members that can be either data or function declaration, and optionally access specifier. • The variable declared inside the class is known as data member and function are known as member functions. • Access specifier are keyword in object oriented language that set the accessibility of classes, method and other member. • Access specifier is one of the following keyword: public, private, protected. C++ Lecture note by hansa halai
  • 8.
    • These specifiermodify the access rights that the member following them acquire:  private members of class are accessible only from within other member of same class or from their friends.  protected members are accessible form members of their same class and from their friends but also from members of their derived classes.  public members are accessible from anywhere the object is visible. • Only member function can have access to private data member and private function of that data. C++ Lecture note by hansa halai
  • 9.
    • #include <iostream> •class Addition { • private: • int num1, num2, sum; • public: • void input() { • cout << "Enter two numbers: "; • cin >> num1 >> num2; • } • void calculate() { • sum = num1 + num2; • } • void output() { • cout << "The sum of " << num1 << " and " << num2 << " is " << sum << std::endl; • } • }; • • int main() { • Addition add; • add.input(); • add.calculate(); • add.output(); • return 0; C++ Lecture note
  • 10.
    Object • Once aclass has been created, we can create variable of that type(class type) by using following syntax which is called object. • Syntax: class_name variable_name; Ex: student s; • we can create any number of objects belonging to that class by declaring more than one object in one statement. This statement are written in main(). • The objects can also be defined by placing their name immediately after the closing brace of the class. C++ Lecture note by hansa halai
  • 11.
    • Syntax: class class_name { …. }object1,object2,…; •Ex: class student { … }s1,s2; C++ Lecture note by hansa halai
  • 12.
    • Accessing classmember: A object can be declared in the main(),and member functions are declared in class in public section so always a member function can be called by using object. • Syntax: object_name.member_function(arguments); Ex: s.getdata(); • A data member can also be access by using object only , if data member is declared as public. • If data member is declared private then you can not access it by using object directly in object. C++ Lecture note by hansa halai
  • 13.
    Defining member function •A member function can be defined in two places in the class: 1. inside the class definition 2. outside the class definition 1) Inside the class definition: To write a member function inside the class instead of only declaration(prototype). Ex: class item { int num; float cost; C++ Lecture note by hansa halai
  • 14.
    public: void getdata(int a,floatb) void putdata(void) { cout<<number; cout<<cost; } }; …. C++ Lecture note by hansa halai
  • 15.
    void (C++) C++ Lecturenote by hansa halai When used as a function return type, the void keyword specifies that the function doesn't return a value.  when used for a function’s parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is universal. the void keyword specifies that the function doesn't return a value. the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the
  • 16.
    2) Outside theclass definition: • To write function we need to declare function inside the class and definition(function body) is written outside the class. • The general form of a member function definition: return_type class_name::function_name(arument) { function body } • The membership label class_name :: tells the compiler that the function function_Name belongs to the class class_name. • :: is scope resolution operator. C++ Lecture note by hansa halai
  • 17.
    USE of scoperesolution operator • // C++ program to show that we can access a global variable • // using scope resolution operator :: when there is a local • // variable with same name • #include<iostream> • using namespace std; • int x; // Global x • int main() • { • int x = 10; // Local x • cout << "Value of global x is " << ::x; • cout << "nValue of local x is " << x; • return 0; • } C++ Lecture note by hansa halai
  • 18.
    Ex: …. void item::getdata(int a,float b) { number=a; coat=b; } void item::putdata(void) { cout<<“number “<<number; cout<< “cost ”<<cost; } … C++ Lecture note by hansa halai
  • 19.
    • // C++program to demonstrate function • // declaration outside class • #include <iostream> • using namespace std; • class Geeks • { • public: • string geekname; • int id; • void printname(); • • // printid is defined inside class definition • void printid() • { • cout <<"Geek id is: "<<id; • } • }; • // Definition of printname using scope resolution operator :: • void Geeks::printname() • { • cout <<"Geekname is: "<<geekname; • } C++ Lecture note by hansa halai
  • 20.
    • int main(){ • • Geeks obj1; • obj1.geekname = "xyz"; • obj1.id=15; • • // call printname() • obj1.printname(); • cout << endl; • • // call printid() • obj1.printid(); • return 0; • } C++ Lecture note by hansa halai
  • 21.
    INLINE FUNCTION • Afunction is used to write code redundancy, as well as to save memory space, when a function is invoked a bunch of task is performed ex matching arguments, matching return type passing control from calling to definition and vice-versa. • If our function body is small than it is a time consuming process therefore C++ introduced concept of inline function C++ Lecture note by hansa halai
  • 22.
    CONT.. • C++ providesinline functions to reduce the function call overhead. An inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of the inline function call. This substitution is performed by the C++ compiler at compile time. An inline function may increase efficiency if it is small. C++ Lecture note by hansa halai
  • 23.
    Syntax: C++ Lecture noteby hansa halai inline return-type functionname (parameters) { // function code }
  • 24.
    C++ Lecture noteby hansa halai
  • 25.
    The compiler maynot perform inlinie in such circumstances as: • If a function contains a loop. (for, while and do- while) • If a function contains static variables. • If a function is recursive. • If a function return type is other than void, and the return statement doesn’t exist in a function body. • If a function contains a switch or goto statement. C++ Lecture note by hansa halai
  • 26.
    Why Inline Functionsare Used? • When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack, and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register, and returns control to the calling function. This can become overhead if the execution time of the function is less than the switching time from the caller function to called function • For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually execute the function’s code. This overhead occurs for small functions because the execution time of a small function is less than the switching time. C++ Lecture note by hansa halai
  • 27.
    Making an outsidefunction inline • We can define a member function outside and still make it inline by just using the qualifier inline in the header line of function definition. • Ex: class item { int number; Float cost; public: void getdata(int a, float b); }; inline void item :: getdata(int a,float b) { number = a; cost = b; } C++ Lecture note by hansa halai
  • 28.
    • #include <iostream> •using namespace std; • inline int fun(int a, int b) • { • return a+b; • } • main() • { • int value=fun(34,67); • Cout<<value; • } C++ Lecture note by hansa halai
  • 29.
    Nesting Member Function •A member function can be called by using its name inside another member function the same class is called nesting member function. • Ex: #include<iostream> using namespace std; class number { private: int a,b,s1,s2; public: int getdata(int m,int n); int sum(); int sub(); C++ Lecture note by hansa halai
  • 30.
    C++ Lecture noteby hansa halai int show() { cout<<"n Enter number1: "; cin>>a; cout<<"n Enter number2: "; cin>>b; cout<<"n Answer of Addition:"<<sum()<<endl; cout<<"n Answer of Addition:"<<sub()<<endl; } }; int number::getdata(int m,int n) { a=m; b=n; }
  • 31.
    C++ Lecture noteby hansa halai int number::sum() { s1=a+b; return(s1); } int number :: sub() { s2=a-b; return(s2); } int main() { number x; x.getdata(10,20); x.show(); return 0; }
  • 32.
    Private Member Function •Generally we declare , data members are in private section and member function in public section, that’s why we call a member function from main() through object. • But if we declare a member function in private section then we can not call directly from the main(), because it’s private function. • To call private function , we have to create public function of that class and we call this private function inside that public function , then the public function called by object from main(). C++ Lecture note by hansa halai
  • 33.
    C++ Lecture noteby hansa halai Ex: #include<iostream> using namespace std; class value { private: int a,b; void getdata(); public: void show(); }; void value::getdata() { cout<<"Enter number1: "; cin>>a; cout<<"Enter number2: "; cin>>b; }
  • 34.
    C++ Lecture noteby hansa halai void value::show() { getdata(); cout<<"Two numbers are "<<a <<"n"<<b; } int main() { value v; v.show(); return 0; }
  • 35.
    Array within class: •The arrays can be used as member variable in a class. • An array is collection of same data type or group of data item that store in a common name. • Syntax: data_type name[size]={list of value}; Like int number[4]={1,2,3,4}; C++ Lecture note by hansa halai
  • 36.
    Ex: C++ Lecture noteby hansa halai #include<iostream> using namespace std; class average { private: int n,A[20]; public: void getdata() { cout<<"Number of element: "; cin>>n; cout<<"Enter the data in array:n "; for(int i=0;i<n;i++) { cout<<"A["<<i<<"]"; cin>>A[i]; } }
  • 37.
    C++ Lecture noteby hansa halai float avg() { float sum=0,ans; for(int i=0;i<n;i++) sum=sum+A[i]; ans=sum/n; cout<<"Average is: "<<ans; } }; int main() { average a; a.getdata(); a.avg(); return 0; }
  • 38.
    Memory allocation forobject • The memory space for objects are allocated when they are declared , not when the class is specified. • For member function , when member function are created , it will occupy the memory space only once when they are defining in a class. • So all objects created for that class can use same member functions , so no separate space is allocated for member functions when the object are created. • For data member , only space for data members is allocated separately for each object when is created. C++ Lecture note by hansa halai
  • 39.
    • The separatespace allocation for data member is essential because the data member will hold different data values for different objects. • For example, a class student have three data members such as reg_no, age, per and two member functions getdata() and show(). • If we create three object S1 ,S2, S3 then, object S1 takes up space for: reg_no , age , per object S2 takes up space for: reg_no , age , per object S3 takes up space for: reg_no , age , per But it will access common member function getdata() and show(), so it will take up space only one time when class is created. C++ Lecture note by hansa halai
  • 40.
    Constructor • Constructor inC++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor. • Constructor is a member function of a class, whose name is the same as the class name. • Constructor is a special type of member function that is used to initialize the data members for an object of a class automatically when an object of the same class is created. • Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as a constructor. • Constructors do not return value, hence they do not have a return type. • A constructor gets called automatically when we create the object of the class C++ Lecture note by hansa halai
  • 41.
    Syntax for Definingthe Constructor Within the Class C++ Lecture note by hansa halai <class-name> (list-of-parameters) { // constructor definition }
  • 42.
    Syntax for Definingthe Constructor Outside the Class C++ Lecture note by hansa halai <class-name>: :<class-name>(list-of-parameters) { // constructor definition }
  • 43.
    C++ Lecture noteby hansa halai #include <iostream> • using namespace std; • class student { • int rno; • char name[50]; • double fee; • public: • // constructor • student() • { • cout << "Enter the RollNo:"; • cin >> rno; • cout << "Enter the Name:"; • cin >> name; • cout << "Enter the Fee:"; • cin >> fee; • } • void display() • { • cout << endl << rno << "t" << name << "t" << fee; • } • };
  • 44.
    • int main() •{ • student s; // constructor gets called automatically when • // we create the object of the class • s.display(); • return 0; • } C++ Lecture note by hansa halai
  • 45.
    C++ Lecture noteby hansa halai • // defining the constructor outside the class • #include <iostream> • using namespace std; • class student { • int rno; • char name[50]; • double fee; • public: • // constructor declaration only • student(); • void display(); • }; • // outside definition of constructor • student::student() • { • cout << "Enter the RollNo:"; • cin >> rno; • cout << "Enter the Name:"; • cin >> name; • cout << "Enter the Fee:"; • cin >> fee; • }
  • 46.
    • void student::display() •{ • cout << endl << rno << "t" << name << "t" << fee; • } • // driver code • int main() • { • student s; • s.display(); • return 0; • } C++ Lecture note by hansa halai
  • 47.
    Static data member •Static variable are normally used to maintain values common to the entire class. • For example, a static data member can be used as a counter that record occurrences of all the objects. • A static member variable has certain characteristic: 1. It automatically initialized zero when the first object is created , no other initialization is permitted. Where a simple variable have initially garbage value. 2. Only one copy of that member is created for entire class and shared by all objects of that class, no matter how many objects are created. 3. It is visible only within a class, but its life time is the entire program. C++ Lecture note by hansa halai
  • 48.
    • Static datamembers are class members that are declared using static keywords. • It is initialized before any object of this class is created, even before the main starts. C++ Lecture note by hansa halai
  • 49.
    C++ Lecture noteby hansa halai • #include <iostream> • #include <string.h> • using namespace std; • // create class of the Car • class Car • { • private: • int car_id; • char car_name[20]; • int marks;
  • 50.
    C++ Lecture noteby hansa halai • public: • // declare a static data member • static int static_member; • Car() • { • static_member++; • } • void inp() • { • cout << " nn Enter the Id of the Car: " << endl; • cin >> car_id; // input the id • cout << " Enter the name of the Car: " << endl; • cin >> car_name;
  • 51.
    • cout <<" Number of the Marks (1 - 10): " << endl; • cin >> marks; • } C++ Lecture note by hansa halai
  • 52.
    • // displaythe entered details • void disp () • { • cout << " n Id of the Car: " << car_id; • cout << "n Name of the Car: " << car_name; • cout << " n Marks: " << marks; • • } • }; C++ Lecture note by hansa halai
  • 53.
    • // initializedthe static data member to 0 • int Car::static_member = 0; • int main () • { • // create object for the class Car • Car c1; • // call inp() function to insert values • c1. inp (); • c1. disp(); • • //create another object • Car c2; • // call inp() function to insert values • c2. inp (); • c2. disp(); • cout << " n No. of objects created in the class: " << Car :: static_m ember <<endl; • return 0; • } C++ Lecture note by hansa halai
  • 54.
    Static member function: •A member function that is declared static has the following properties:  A static function can have access to only other static members(function or variable) declared in the same class.  A static member function can be called using the class name. like, class_name :: Function_name(); test :: getdata(); C++ Lecture note by hansa halai
  • 55.
    Ex: C++ Lecture noteby hansa halai #include<iostream> using namespace std; class stat_fun { int obj; static int count; public: void stat() { obj=++count; } void showObject() { cout<<"n object number is: "<<obj; } static void showcount() { cout<<"ncount object is:"<<count; } };
  • 56.
    C++ Lecture noteby hansa halai int stat_fun::count; int main() { stat_fun o1,o2; o1.stat(); o1.stat(); stat_fun::showcount(); stat_fun o3; o3.stat(); stat_fun::showcount(); return 0; }
  • 57.
    Arrays of object: •As an array can be of any data type including struct. Similarly, we can also have arrays of variable that are of the type class. Such variables are called array of objects. • For example: class student { private: float per; public: int regno,age; void getdata(); void show(); }; For this class if we required 100 student , then we are not declare different s1,s2,…,s100 object because it’s very critical task. For this problem we use array of object. C++ Lecture note by hansa halai
  • 58.
    Ex: C++ Lecture noteby hansa halai #include<iostream> using namespace std; class student{ char name[15]; float age; public: void getdata(); void putdata(); }; void student :: getdata() { cout<<"Enter Name: "; cin>>name; cout<<"Enter Age: "; cin>>age; } void student :: putdata() { cout<<"Name: "<<name<<"n"; cout<<"Age: "<<age <<"n"; }
  • 59.
    C++ Lecture noteby hansa halai const int size=2; int main() { student s[size]; // array of object for(int i=0;i<size;i++) { cout<<"Detail of student"<<i+1<<"n"; s[i].getdata(); } cout<<"n"; for(int i=0;i<size;i++) { cout<<"nnStudent"<<i+1<<"n"; cout<<"--------n"; s[i].putdata(); } return 0; }
  • 60.
    Object as functionargument: • Like any other data type, an object may be used as a function argument. This can be done in two way: 1. A copy of the entire object is passed to the function, which is called call by value. 2. Only the address of the object is transferred to the function, which is called call/pass by reference. C++ Lecture note by hansa halai
  • 61.
    EX: C++ Lecture noteby hansa halai #include<iostream> using namespace std; class Square{ int x; public: void getdata(int m) { x=m; } int answer(Square s) { x=s.x*s.x; } void show() { cout<<"Answer is:"<<x; } };
  • 62.
    C++ Lecture noteby hansa halai int main() { Square s1,s2; s1.getdata(6); s2.answer(s1); s2.show(); return 0; }
  • 63.
    Returning objects: • Afunction can not only receive objects as arguments but also can return them. • Like: C++ Lecture note by hansa halai #include<iostream> using namespace std; class SUM { int x; public: void getdata(int m) { x=m; }
  • 64.
    C++ Lecture noteby hansa halai SUM sum(SUM s) { SUM temp; temp.x=x+s.x; return(temp); } void show() { cout<<"Answer is: "<<x; } }; int main() { SUM s1 ,s2,s3; s1.getdata(4); s2.getdata(10); s3=s1.sum(s2); s3.show(); return 0; }
  • 65.
    Friendly functions: • Dueto ‘data hiding ’ feature of c++, the private data members of class can not be access outside the class. So a function which are not member of the class, they can not be access the private data of that class. • In c++, there is facility available to access private data of class even if it is not member function of that class. It is possible bye using friend function. • As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. C++ Lecture note by hansa halai
  • 66.
    • To makean outside function “friendly” to class, declare the function as friend of that class. • The friend functions are declared by using friend keyword. • Syntax: friend return_type function_name(arg_list); • Generally arguments in friend functions are object type. because of outside the class a data member can not directly access, so a object can access it. • A function can be declared as friend for any number of class. It can not be member function of any class. It have full rights to access private data of the class. C++ Lecture note by hansa halai
  • 67.
    • Advantage ofhaving friend function: 1. We can able to access the other class members in our class, if we use friend keyword. 2. We can access the members without inheriting the class. • Disadvantage: 1. Maximum size of memory will occupied by object according to the size of friend member. 2. Break the concept of ‘data hiding’ in oop. C++ Lecture note by hansa halai
  • 68.
    • Characteristic offriend function: 1. It is not in the scope of the class which it has been declared as friend. 2. It can not be called using the object of that class. It can be invoked like a normal function without the help of object. 3. It can not access data member directly, it must be use object with dot(.) operator and data member. 4. Normally it has object as argument. C++ Lecture note by hansa halai
  • 69.
    Ex: C++ Lecture noteby hansa halai #include<iostream> using namespace std; class MEAN{ int n1,n2; public: void getdata() { cout<<"Enter num1: "; cin>>n1; cout<<"Enter num2: "; cin>>n2; } friend float ans(MEAN m); };
  • 70.
    C++ Lecture noteby hansa halai float ans(MEAN m) { return float(m.n1+m.n2)/2; } int main() { MEAN m1; m1.getdata(); cout<<"Answer is: "<<ans(m1); return 0; }
  • 71.
    Const member function: •Function member can made constant by writing word const keyword between header of the function and body. • Constant member function means it can not modify the object. • normally function member which are not supposed to modify the object should be made constant so that there are no chance that accidently function member modifies the object. • void mul(int , int) const; // constant function { Body statement.. } C++ Lecture note by hansa halai
  • 72.
    Pointer to member: •Just like pointer to normal variable and function , we can have pointer to class member function and member variable. • Syntax for declare pointer data member: data_type class_name::*pointer_name; • Ex int A ::* p; • You can initialize p like this also: • syntax: data_type class_name::*pointer_name=&class_name::data_member • Ex: int A::*p=&A::m; C++ Lecture note by hansa halai
  • 73.
    • Likewise, youcan access the data member through a pointer to a class. • Ex: A *p1 =new A; int n =p1->*p; // assign to n the value of p1->m p1->*p=5; // assign the value of 5 to p1->m • Pointer to member functions are one of the c++’s rarely used features, while they do not have widely applicability, some time member function pointer are useful to solve certain problems. • Member function pointer can not be dereferenced directly by themselves .they must be called on behalf of some object. C++ Lecture note by hansa halai
  • 74.
    • To declarea pointer to member function you give the prototype of function it can point to,as before but the name of this function is replaced by a construction that scopes the pointer – you give it the name of the class whose member function it can point to. • Syntax: return_type (class_name::*pointer_name)(argument_list) • You dereference a member function pointer by using .* or ->*, supplying a reference or pointer to an object on the left, as appropriate , and the function pointer on the right. • Note that member function does not have the same data type as nonmember function that has the same number and type of argument and the same return type. C++ Lecture note by hansa halai
  • 75.
    Ex: #include<iostream> using namespace std; classtest{ public: int a; void fun(int b) { cout<<"The value of b is: "<<b<<endl; } }; int main() { int test::*p=&test::a; // pointer to data member declaration C++ Lecture note by hansa halai
  • 76.
    void(test::*p1)(int)=&test::fun; // pointerto function declaration test T; T.*p=10; cout<<"The value of a is:"<<T.*p<<endl; (T.*p1)(20); } C++ Lecture note by hansa halai