classes and objects in C++
-
Upload
halaihansaika -
Category
Education
-
view
442 -
download
0
Transcript of classes and objects in C++
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 possiblethe built-in data type and also provide a facility to hidedata.
C++ Lecture note by hansa halai
Class• A class is a way to bind data and associated function together.
• A class is an expanded concept of a data structure, instead ofholding 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, withthe 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 canbe either data or function declaration, and optionallyaccess specifier.
• The variable declared inside the class is known as datamember and function are known as memberfunctions.
• Access specifier are keyword in object oriented languagethat set the accessibility of classes, method and othermember.
• 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 followingthem acquire:
private members of class are accessible only from within othermember of same class or from their friends.
protected members are accessible form members of theirsame class and from their friends but also from members of theirderived classes.
public members are accessible from anywhere the object isvisible.
• By default, all members of class declared with the class keyword haveprivate access for all its member. Therefore, any member that isdeclared before one other class specifier automatically has privateaccess.
• Only member function can have access to private data member andprivate function of that data. C++ Lecture note by hansa halai
Object
• Once a class has been created, we can create variable ofthat type(class type) by using following syntax which iscalled object.
• Syntax:
class_name variable_name;
Ex:
student s;
• we can create any number of objects belonging to thatclass by declaring more than one object in one statement.This statement are written in main().
• The objects can also be defined by placing their nameimmediately 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
2) Outside the class definition:
• To write function we need to declare function insidethe class and definition(function body) is writtenoutside 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 thecompiler that the function function_Name belongsto the class class_name.
• :: is scope resolution operator.
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
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
{….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
Nesting Member Function
• A member function can be called by using its name inside anothermember function the same class is called nesting memberfunction.
• 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 sectionand member function in public section, that’s why we calla member function from main() through object.
• But if we declare a member function in private sectionthen we can not call directly from the main(), because it’sprivate function.
• To call private function , we have to create public functionof that class and we call this private function inside thatpublic function , then the public function called by objectfrom 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 aredeclared , not when the class is specified.
• For member function , when member function are created, it will occupy the memory space only once when they aredefining in a class.
• So all objects created for that class can use same memberfunctions , so no separate space is allocated for memberfunctions when the object are created.
• For data member , only space for data members isallocated separately for each object when is created.
C++ Lecture note by hansa halai
• The separate space allocation for data member is essentialbecause the data member will hold different data values fordifferent objects.
• For example, a class student have three data members suchas reg_no, age, per and two member functionsgetdata() 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 whenclass is created.
C++ Lecture note by hansa halai
Static data member
• Static variable are normally used to maintain valuescommon to the entire class.
• For example, a static data member can be used as acounter that record occurrences of all the objects.
• A static member variable has certain characteristic:
1. It automatically initialized zero when the first object iscreated , no other initialization is permitted. Where asimple variable have initially garbage value.
2. Only one copy of that member is created for entire classand shared by all objects of that class, no matter howmany objects are created.
3. It is visible only within a class, but its life time is theentire program.
C++ Lecture note by hansa halai
Ex:
C++ Lecture note by hansa halai
#include<iostream>using namespace std;
class student{int roll_no;char name[15];static char course[15];
public:void getdata() {
cout<<" Enter roll number:";cin>>roll_no;cout<<" Enter Name:";cin>>name;
}void putdata() {
cout<<"Student Roll Number: "<<roll_no<<"\n";cout<<"Student Name: " <<name<<"\n";cout<<"Student Class: " <<course<<"\n";
}};
C++ Lecture note by hansa halai
char student::course[15]="BCA";int main(){
int n;cout<<"Enter number of student you want...";cin>>n;
student s[n]; // array of objectfor(int i=0;i<n;i++){
cout<<"Detail of student"<<i+1<<"\n";s[i].getdata();
}cout<<"\n";for(int i=0;i<n;i++){
cout<<"\n\nStudent"<<i+1<<"\n";cout<<"--------\n";s[i].putdata();
}return 0;
}
Static member function:
• A member function that is declared static has thefollowing properties:
A static function can have access to only other staticmembers(function or variable) declared in the same class.
A static member function can be called using the classname.
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 notdeclare different s1,s2,…,s100 object because it’s very criticaltask. 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 objectfor(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<<"\n\nStudent"<<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 afunction 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 thefunction, 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 datamembers of class can not be access outside the class. So afunction which are not member of the class, they can notbe access the private data of that class.
• In c++, there is facility available to access private data ofclass even if it is not member function of that class. It ispossible bye using friend function.
• As the name suggests, the function acts as a friend to aclass. As a friend of a class, it can access its private andprotected members.
C++ Lecture note by hansa halai
• To make an outside function “friendly” to class, declare thefunction 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 directlyaccess, 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 rightsto 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 ourclass, if we use friend keyword.
2. We can access the members without inheriting theclass.
• 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 wordconst keyword between header of the function andbody.
• Constant member function means it can not modify theobject.
• normally function member which are not supposed tomodify the object should be made constant so that thereare no chance that accidently function member modifiesthe 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 canhave pointer to class member function and membervariable.
• 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 apointer 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++’srarely used features, while they do not have widelyapplicability, some time member function pointer areuseful to solve certain problems.
• Member function pointer can not be dereferenced directlyby themselves .they must be called on behalf of someobject.
C++ Lecture note by hansa halai
• To declare a pointer to member function you give theprototype of function it can point to,as before but the nameof this function is replaced by a construction that scopes thepointer – you give it the name of the class whose memberfunction 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 typeas nonmember function that has the same number and typeof 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