CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC...

14
A Class is a way to bind data items (variables) describing an entity and its associated methods (functions) together under one name. CLASSES AND OBJECTS class class_name { private : variables; functions; public : variables; functions; protected : variables; functions; } ; braces semicolon colon Access specifiers keyword Data Members Member Functions colon colon Example: class student { private: int roll; char name[20]; float marks; public: void getdata() { cin>>roll; gets(name); cin>>marks } void showdata() { cout<< roll; cout<<name; cout<<marks; } } s1, s2 ; Global objects of class student s1 s2

Transcript of CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC...

Page 1: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

A Class is a way to bind data items (variables) describing an entity and its associated methods (functions) together under one name.

CLASSES AND OBJECTS

class class_name { private : variables; functions; public : variables; functions; protected : variables; functions; } ;

braces

semicolon

colon

Access specifiers

keyword

Data Members

Member Functions

colon

colon

Example:

class student { private: int roll; char name[20]; float marks; public: void getdata() { cin>>roll; gets(name); cin>>marks } void showdata() { cout<< roll; cout<<name; cout<<marks; } } s1, s2 ;

Global objects of class student

s1

s2

Page 2: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

A class contains data members and member functions with either private, public or protected visibility/access.

Generally data members (variables) are private and member functions are public.

Any member functions inside a class can access all data members and invoke other member functions also irrespective of their visibility mode.

Declaration of a class does not allocate memory to its data members.

A class is a template/blueprint for objects. A class is a derived data type.

Objects are instances of a class i.e. objects are variables of the class type.

When objects are declared, memory is reserved for a copy of each data member (variable) within the class.

CLASSES AND OBJECTS

Page 3: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS

Once a class is defined, its objects can now be created using the following syntax : class_name object_name; For example an object of the student class can be declared as follows: void main() { student stu1,stu2; // objects stu1.getdata(); stu1.putdata(); stu2.getdata(); stu2.putdata(); } Each object created from a class contains separate copy of data members (variables) and has

different set of values for different objects. Outside the class, public data members and member functions can be accessed/invoked

through the object of the class using the dot operator (.) When invoked, member functions work upon the data members (variables) of the object that

is used to invoke the member function. Private and protected members cannot be accessed outside the class.

roll name marks

stu1

roll name marks

stu2

Page 4: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

ACCESS SPECIFIERS / VISIBILITY MODES 1. Private - These data members and member functions are

accessible from only within the class. These members are hidden from outside world.

2. Public - These data members and member functions are accessible from within the class as well as from anywhere outside the class definition through an object of the class using the dot operator.

3. Protected - These data members and member functions are accessible from within the class and also within all the derived or subclasses of the class.

Note: The difference between Structure and Class is that

members of a structure are public by default unlike a class where members are private by default. If you do not specify any visibility mode then all the members are private, such a class is completely hidden from the outside and will not serve any purpose.

class demo { private : int X; void func_X() {cout<<X;} public : int Y; void func_Y() {cout<<Y;} protected : int Z; void func_Z() {cout<<Z;} }; void main() { demo obj; obj.X = 5 ; // invalid, private member obj.Y = 5 ; // Y is assigned 5 obj.Z = 5 ; // invalid, protected member obj.func_X() // invalid, private member obj.func_Y() // output 5 obj.func_Z() // invalid, protected member }

Page 5: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

DEFINING MEMBER FUNCTIONS

s1 s2

Function declaration inside the class ( INLINE FUNCTION) class Student { int roll;

char name[20]; float marks;

public: void getdata()

{ cin >> roll ; gets(name); cin>>marks; } void putdata()

{ cout << roll<< name <<marks<<endl; } } ; void main() { Student s1, s2;

s1.getdata(); s2.getdata(); s1.putdata(); s2.putdata();

}

Note: Only small functions can be made Inline

Function declaration outside the class using scope resolution (::) class Student { int roll;

char name[20]; float marks;

public: void getdata(); void putdata();

} ; void Student :: getdata()

{ cin >> roll; gets(name); cin>>marks; } void Student :: putdata()

{ cout << roll<< name <<marks<<endl; } void main() { Student s1, s2;

s1.getdata(); s2.getdata(); s1.putdata(); s2.putdata();

}

Ques: How is a member function of the class different from an ordinary function?

Page 6: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

NESTING OF MEMBER FUNCTIONS

#include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> class student {

int roll; char name[20]; int marks; char grade; char findgrade();

public: void getdata(); void putdata();

};

void student::getdata() {

cout<<"enter your roll no "; cin>>roll; cout<<"enter your name "; gets(name); cout<<"enter your marks \n"; cin>>marks; grade = findgrade(); // invoke fn to return grade

} void student::putdata() {

cout<<"Roll :"<<roll<<endl; cout<<"Name: "<<name<<endl; cout<<"Marks :"<<marks<<endl; cout<<"Grade: "<<grade<<endl;

}

char student :: findgrade() {

char ch; if (marks>=90) ch='A'; else if (marks>=80) ch='B'; else if (marks>=60) ch-'C'; else ch='D'; return ch;

} void main() {

student st; st.getdata(); st.putdata();

}

St

Page 7: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

NESTING OF MEMBER FUNCTIONS

#include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> class student {

int roll; char name[20]; int marks[5]; char stream[20]; void findstream();

public: void getdata(); void putdata();

};

void student::getdata() { cout<<"enter your roll no ";

cin>>roll; cout<<"enter your name "; gets(name); cout<<"enter your marks in phy, chem, maths, eng and c++ resp. \n"; for(int i=0;i<5;i++) {cin>>marks[i];} findstream(); //invoke fn to assign stream

} void student::putdata() { cout<<"Roll :"<<roll<<endl;

cout<<"Name: "<<name<<endl; cout<<"Marks in 5 subjects:- \n"; for(int i=0;i<5;i++) {cout<<marks[i]<<endl;} cout<<"Stream: "<<stream;

}

void student :: findstream() { int sum=0; float per; for(int i=0;i<5;i++) { sum+=marks[i]; } per=float(sum)/5; if (per>=96) strcpy(stream,"computer science"); else if (per>=91 && per<=95.9) strcpy(stream,"elctronics"); else if (per>=86 && per<=90.9) strcpy(stream,"mechanical"); else if (per>=81 && per<=85.9) strcpy(stream,"electrical"); else if (per>=76 && per<=80.9) strcpy(stream,"chemical"); else if (per>=71 && per<=75.9) strcpy(stream,"civil"); else strcpy(stream,"no stream"); } void main() { student st;

st.getdata(); st.putdata();

} St

roll

name

Marks[0]

stream

Marks[1]

Marks[2]

Marks[3]

Marks[4]

Page 8: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

ARRAY OF OBJECTS #include<iostream.h> #include<conio.h> #include<stdio.h> #define max 3 class bank {

int account_no; char name_of_depositor[20]; char type_of_account; double balance;

public: int return_accno(); void readdata(); void deposit(); void withdraw(); void display();

}; int bank :: return_accno() { return account_no; } void bank :: deposit() { double amount; cout<<"enter the amount you want to deposit "; cin>>amount; balance+=amount;

}

void bank::display() {

cout<<"account no "<<account_no<<endl; cout<<"name: "<<name_of_depositor<<endl; cout<<"type of account "<<type_of_account<<endl; cout<<"initial balance "<<balance<<endl;

} void main() { bank b[max] ; int accno , ch ; char flag ;

for(int i=0; i<max; i++ ) b[i].readdata();

do{ cout<<"enter your account no "<<endl; cin>>accno;

cout<<"1.Deposit"<<endl; cout<<"2.Withdraw"<<endl; cout<<"3.Display"<<endl; cout<<"4.Exit"<<endl; cout<<"enter your choice "; cin>>ch; flag='n'; for(int j=0;j<max;j++) { if(b[j].return_accno()==accno) { flag='y';

switch(ch) { case 1 : b[j].deposit();break; case 2 : b[j].withdraw();break; case 3 : b[j].display(); }

} } if (flag=='n') cout<<"invalid account number";

} while(ch!=4); }

void bank:: withdraw() {

double amount; cout<<"enter the amount you want to withdraw "; cin>>amount; if(balance-amount>=1000) balance-=amount; else cout<<"you can't withdraw this much amount ";

} void bank :: readdata() {

cout<<"enter your account number "; cin>>account_no; cout<<"enter your name "; gets(name_of_depositor); cout<<"enter the type of account ('S' for saving and 'C' for current) "; cin>>type_of_account; cout<<"enter your initial balance "; cin>>balance;

}

b[0] b[1] b[2]

Page 9: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

PASSING OBJECTS TO FUNCTIONS

#include<iostream.h> class time {

int hours; int minutes;

public: void gettime(int,int); void showtime(); void addtime(time, time& );

}; void time :: gettime(int h, int m) { hours=h;

minutes=m; } void time ::showtime() { cout<<endl<<hours<<":"<<minutes<<endl; }

void time :: addtime(time t1 , time &t2) { hours=t1.hours+t2.hours+(t1.minutes+t2.minutes)/60; minutes=(t1.minutes+t2.minutes)%60; } void main() { time ft, st, tt; int hh,mm;

cout<<“\nenter first time in hours and minutes "; cin>>hh>>mm; ft.gettime(hh,mm); cout<<“\nenter second time in hours and minutes "; cin>>hh>>mm; st.gettime(hh,mm); cout<<endl<<"total time is "; tt.addtime ( ft , st ); tt.showtime();

}

tt

4

25

ft St / t2

2

50

7

15

4

25

t1

Objects can be passed to functions : By Value or By Reference

Page 10: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

RETURNING OBJECTS FROM FUNCTIONS

#include<iostream.h> class time {

int hours; int minutes;

public: void gettime(int,int); void showtime(); time addtime(time);

}; void time :: gettime(int h, int m) { hours=h;

minutes=m; } void time ::showtime() { cout<<endl<<hours<<":"<<minutes<<endl; }

time time::addtime(time t) {

time tt; tt.hours=hours+t.hours+(minutes+t.minutes)/60; tt.minutes=(minutes+t.minutes)%60; return tt;

} void main() { time ft, st, tt; int hh,mm;

cout<<“\nenter first time in hours and minutes "; cin>>hh>>mm; ft.gettime(hh,mm); cout<<“\nenter second time in hours and minutes "; cin>>hh>>mm; st.gettime(hh,mm); cout<<endl<<"total time is "; tt = ft.addtime( st ); tt.showtime();

}

tt

4

25

ft st

2

50

7

15

2

50

7

15

t

tt

Page 11: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

IMPORTANT DEFINITIONS

Object Oriented Programming System: OOPS enables us to think in terms of objects and the interaction between objects. All real-world entities correspond to Objects. Objects have State (Data) and Behaviour (Functions). For example : Dogs have state (name, colour, breed) and behaviour (barking, fetching, wagging). Similarly, Bicycles also have state (wheels, gear, pedal ) and behaviour (start, move, stop).

Class : A Class is a group of objects that share common properties and

relationships. Class binds data and its associated functions under one unit there by enforcing encapsulation. A class is a blueprint/template for objects. It is a user defined data type used to implement an abstract object also called abstract data type (ADT).

Object: An Object is an instance of a class. Object represent a real world entity

which can store data and has its interface through functions.

Page 12: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

IMPORTANT DEFINITIONS

Data Encapsulation: Wrapping up data and associated functions into one single unit called Class is referred to as Data Encapsulation

Data Hiding : Hiding intricate details from the end user is called data hiding. For

example: The private and protected members of a class remain hidden from outside world and there by helps in implementing data hiding.

Data Abstraction: Abstraction is the concept of bringing essential features to the

surface without going into the background details. For example : A public function is invoked through the object of the class from outside. But its coding ( what data and functions it is in turn using ) is not known to the outside world.

Modularity : The act of partitioning a complex program into simpler fragments

called modules is called as modularity. It reduces the complexity to some degree and it creates a number of well defined boundaries within the program .

Page 13: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

Object Oriented Programming Procedural Oriented Programming

Emphasis is on data ( objects / variables) Emphasis is on doing things ( functions )

Data hiding feature prevents accidental change in values. Access specifiers make data more secure.

Presence of global variables increase chances of accidental change in values, Data is less secure.

Follows Bottom-Up approach in program design

Follows Top-Down approach in program design

Special features like Encapsulation, Abstraction, Polymorphism, Inheritance are present

Special features are not present

Reusability of code ( eg. classes, inheritance) Limited reuse of code

Example of OOP are : C++, JAVA, VB.Net, C#.NET

Example of POP are : C, VB, Fortran, Pascal

Page 14: CLASSES AND OBJECTS€¦ · CLASSES AND OBJECTS . DECLARING OBJECTS OF CLASS AND ACCESSING PUBLIC MEMBERS Once a class is defined, its objects can now be created using the following

ADVANTAGES AND DISADVANTAGES OF OBJECT ORIENTED PROGRAMMING OVER EARLIER PROGRAMMING METHODOLOGIES

Some of the advantages of object-oriented programming include: 1. Improved software productivity because object-oriented programming is modular,

extensible and reusable. 2. Improved software maintainability since the design is modular, and a part of the

system can be updated in case of issues . 3. Faster development is possible because of reusability of code. 4. Lower cost of development 5. Higher-quality software because more time and resources can now be used in the

testing of the software. Some of the disadvantages of object-oriented programming include: 1. Complex to create programs based on interaction of objects. 2. Larger program size than procedural programs.