Your SlideShare is downloading. ×
0
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Lecture07
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Lecture07

166

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
166
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Lecture 07 Classes and ObjectsLearn about:i) Relationship between class and objectsii) Data members & member functionsiii) Member access specifier: private & publiciv) Objects as physical and user defined data types 1
  • 2. Class and Objects• What is a class? – Class is a blue print or a prototype of OBJECT – Based on which any number of objects can be created. – EG : to build a new car • step 1 : create a prototype • step 2 : can build any number of cars based on the prototype • All the cars will have the features of the prototype prototype Car1 Car2 Car3 2/15
  • 3. How a class will look Like? Student class name idnum data members gpa setData member functions showDataA class declaration describes a set of related data and associatedfunction which work on those data. 3/15
  • 4. A Simple Class: Class Declaration (Option 1)#include <iostream.h>class Student // class declaration{ can only be accessed within class private: int idNum =0; //class data members double gpa = 0.0; accessible from outside andwithin class public: void setData(int id, double result) { idNum = id; gpa = result; } Object1 Object2 void showData() { cout << ”Student Id is ” << idNum << endl; cout << ”GPA is " << gpa << endl; }}; 4/15
  • 5. A Simple Class: Class Declaration (Option 2)#include <iostream.h>class Student // class declaration{ private: Explanation int idNum; //class data double gpa; public: void setData(int, double) ; scope resolution operator void showData();};// Implementation of member functionsvoid Student :: setData(int id, double result) { idNum = id; gpa = result; }void Student :: showData() { cout << ”Student Id is ” << idNum << endl; cout << ”GPA is " << gpa << endl; } 5/15
  • 6. Scope resolution Operator• Operator ---> ::• Definition : It tells the compiler the scope of the function – The function belongs to which class• Where it can be used? – A function can be written within a class or outside a class. – When written outside the class, the scope of the function should be defined. Example 6/15
  • 7. Scope resolution operator : DifferenceClass xyz Class xyz{ private: { private: int id; char grade; int id; char grade; public: public: void set ( ) void set ( ) { id = 10; } grade = ‘A’; void xyz::set ( ) { id = 10; grade = ‘A’;} }}; 7/15
  • 8. A Simple Class: Object Definition and Manipulationvoid main() objects’ creation or instantiation{ Student s1, s2; s1.setData(10016666, 3.14); s2.setData(10011776, 3.55); s1.showData(); s2.showData(); accessing or invoking member functions} Syntax: object_name . member_function_name member access operator 8/15
  • 9. A Simple Class:Sending a message to an object 1 . Through which objects interact with each otherStudent:s1 2. Whom - object name idnum action - method name gpa parameterssetData showData()showData A C++ statement: s1.showData() 9/15
  • 10. A Simple Program: How it works? Student s1, s2;CLASS: OBJECTS: Student Student:s1 Student:s2 int idnum; int idnum; int idnum; double gpa; double gpa; double gpa;void setData(int, void setData(int, void setData(int,double); double); double);void showData(); void showData(); void showData(); 10/15
  • 11. A Simple Program: How it works? What is the output ?s1.setData(10016666, 3.14); s2.setData(10011776, 3.55); s1.showData(); s2.showData(); Student:s1 Student:s2 idnum 10016666 idnum 10011776 gpa 3.14 gpa 3.55 void setData(int, void setData(int, double); double); void showData(); void showData(); 11/15
  • 12. A simple program example#include <iostream.h> void main() {class Student Student aStudent;{ private: aStudent.setIdNum(10019999); int idNum; char studName[20]; double gpa; aStudent.setName(‘Robbie’);public: aStudent.setGPA(3.57); void displayStudentData(); void setIdNum(int); aStudent.displayStudentData(); void setName(char[]); void setGPA(double); }};//Implementation - refer to notes page 2(Lecture 7). 12/15
  • 13. A simple program example#include <iostream.h> void main()class Distance {{ private: Distance dist1, dist2; int feet; dist1.setDistance(11, 6.25); float inches; dist2.getDistance(); public: void setDistance(int ft, float in) //display lengths { feet = ft; inches = in; } cout << "ndist1 = "; void getDistancet() dist1.showDistance(); { cout << "nEnter feet: "; cin>>feet; cout << endl; cout << "Enter inches: "; cin>>inches; } cout << "ndist2 = "; void showDistance() dist2.showDistance(); { cout << feet << "-" << inches << "; } cout << endl;}; } 13/15
  • 14. UML - Unified Modeling Language• UML are used for drawing models – Class diagram is one of the types of UML diagrams. – They Identify classes and their relationships• How to draw class diagram? Car Wheel Association model model color 1 n width speed drive ( ) change ( ) stop ( ) More than 1 turn( ) Multiplicity 14/15
  • 15. OOP Revisited 1. Major benefit - close correspondence between the real-world things being modeled – Everything about a real-world thing is included in its class description. ( characteristics & behaviour )• This makes it easy to conceptualize a programming problem. You simply – figure out what parts of the problem can be most usefully represented as objects, and then – put all the data and functions connected with that object into the class.• For small programs, you can often proceed by trial and error.• For larger programs, you need to learn Object-Oriented Design (OOD) methodologies. 15/15
  • 16. Write a program to add two numbers ( Unstructured Programming)#include <iostream.h>void main( ){ int a,b,c;cin >> a >> b;c= a+b;cout<<c;c=a-b;cout<<c;} 16/15
  • 17. Write a program to add two numbers (structured Programming)#include <iostream.h> void main( )int a,b,c; {input ( ){ cin>>a>>b;} input( );add() add( );{ c= a+b; } print( ); sub( );sub( ) print( );{c= a-b;} }print() 17/15{cout<<c;}
  • 18. OOP#include <iostream.h>class sample{Private : void main( )int a,b,c; {Public: sample s;input ( ){ cin>>a>>b;} s.input( );add() s.add( );{ c= a+b; } s.print( );sub( ){c= a-b;} s.sub( );print() s.print( );{cout<<c;} }}; 18/15
  • 19. Constructors and DestructorsLearn about:i) Constructorsii) Destructorsiii) When and how constructors & desctructors arecalled? 19
  • 20. What is a Constructor?• A member function that is executed automatically each time an object is created.• Must have exactly the same name as the class name.• No return type is used for constructors.• Purpose: Used to initialize the Data Members Example Next Slide 20/15
  • 21. Constructors: Definition#include <iostream.h>class Student // class declaration{ private: int idNum; //class data double gpa; public: Student() { cout<<“An object of Student is created!!”<<endl; } void setData(int, double) ; void showData();};// Implementation of member functions 21/15
  • 22. Constructors: Definition#include <iostream.h>class Student // class declaration{ : public: Student() { cout<<“An object of Student is created!!”<<endl; } :};// Implementation of member functionsvoid main(){ Student s1, s2; Constructor is called twice!! :} What is the output? 22/15
  • 23. Types of Constructor?• Two types : default & multi argument constructor• A constructor without argument is called a default constructor.• A constructor can be overloaded. Ie ( there can be another constructor with same name )• One of the most common tasks a constructor does is to initialize data members. For example, Student s1; Student:s1 Student() idNum gpa 0 { idNum = 0; 0.0 gpa = 0.0; } Student() setData(); showData();Initialize to default values. 23/15
  • 24. Types of Constructor• A multi-argument constructor can initialize data members to values passes as arguments. For example, Student(int num, double result) Student s1(1001, 3.14); { idNum = num; Student:s1 gpa = result; } idNum 1001 gpa 3.14 Student() setData();Initialize with arguments showData();passed to it 24/15
  • 25. Default and overloaded Constructor: A simple program example#include <iostream.h> void main()class Student {{ private: Student s1; int idNum; s1.setData(6666, 3.14); double gpa;public: Student s2(1776, 3.55); Student() : { cout<<“An object is created”<<endl; } } Student:s1 Student:s2 Student(int id, double result) idNum 6666 idNum 1776 { idnum = id; gpa = result; } gpa 3.14 gpa 3.55 void setData(); void showData();}; Student() Student()//Implementation - refer to notes page 3 setData(); setData();(Lecture 8). showData(); 25/15 showData();
  • 26. Constructor: Initializer list• Preferred way of initializing the data members using constructors is as follows:• Student(): idnum(0), gpa(0.0) { } Student(int id, double result): idnum(id), gpa(result) { } Counter() : count(0) { } SomeClass() : m1(7), m2(33), m3(4) { } Student( ) Student ( int id,double result) { idnum = 0; gpa =0.0;} { idnum = id; gpa = result;} 26/15
  • 27. Constructor: Other Example#include <iostream.h> void main() { Counter c1, c2;class Counter{ private: cout << "nc1="<< c1.get_count(); int count; cout << "nc2=" << c2.get_count(); public: c1.inc_count(); //increment c1 Counter() : count(0) c2.inc_count(); //increment c2 { //empty body*} c2.inc_count(); //increment c2 void inc_count() { count++; } cout << "nc1=" << c1.get_count(); int get_count() { return count; } cout << "nc2=" << c2.get_count();}; What is the output?// refer to page 4, Lecture 8 } 27/15
  • 28. What is a Destructor?• A member function that is called automatically each time an object is destroyed.• Has the same name as the constructor but is preceded by a tilde (~).• No return type and take no arguments.• Purpose : de-allocate the memory allotted for the data members• EG : class xyz { private : data members 28/15 public:
  • 29. Destructor: Definition#include <iostream.h>class Student // class declaration{ private: int idNum; //class data double gpa; public: ~Student() { cout<<“An object has been destroyed!!”<<endl; } void setData(int, double) ; void showData();};// Implementation of member functions 29/15
  • 30. Constructors & Destructors: A Simple Example#include <iostream.h> void main() { Student s1, s2;class Student }{ private: int idNum; public: Student() { cout<<“Object created.”<<endl;} Output: Object created. ~Student() Object created { cout<<“Object destroyed!”<<endl;} Object destroyed!}; Object destroyed!// refer to page 6, Lecture 8 30/15
  • 31. Constructors and Destructors: Global, Static and Local Objects• Constructors for global objects are called when the programbegin execution. Destructors are called when program terminates.• Constructors for automatic local objects are called whenexecution reaches the point where the objects are defined.Destructors are called when objects leave their scope.• Constructors for statics objects are called only once whenexecution reaches the point where the objects are defined.Destructors are called when program terminates. 31/15
  • 32. Global, Static and Local Objects class Test { private: int data; public: Test (int value); ~Test(); ...};Test :: Test (int value){ data = value; cout<<“ Object”<<data<<“ constructor”; }Test::~Test(){ cout<<“Object”<,data<<“ destructor”<<endl; At this level, first object invokesTest first (1); its constructor ( global ) Cont… in the next slide 32/15
  • 33. Global, Static and Local Objectsvoid main(){ cout<<“ (global created before main)”<<endl; Test second(2); second object invokes cout<<“ (local automatic created in main)”<<endl; its constructor static Test third(3); third object invokes cout<<“ (local static created in main)”<<endl; its constructor func(); // function func is invoked link forth object invokes { Test forth(4); its constructor cout<<“ (local automatic crated in inner block inmain)”<<endl; forth object invokes second, sixth, third, } its destructor and first object invokes} 33/15 its destructor respectively
  • 34. Global, Static and Local Objectsvoid func() fifth object invokes{ Test fifth(5); its constructor cout<<“ (local automatic created in func)”<<endl; static Test sixth(3); sixth object invoke cout<<“ (local static created in func)”<<endl; its constructor} fifth object invokes its destructor 34/15
  • 35. Global, Static and Local ObjectsOutput:Object 1 constructor (global created before main)Object 2 constructor (local automatic created in main)Object 3 constructor (local static created in main)Object 5 constructor (local automatic created in func)Object 6 constructor (local static created in func)Object 5 destructorObject 4 constructor (local automatic created in inner block in main)Object 4 destructorObject 2 destructorObject 6 destructorObject 3 destructorObject 1 destructor Another example in the next slide 35/15
  • 36. Global, Static and Local ObjectsTest first (1) First object invokesvoid main() its constructor{ cout<<“ (global created before main)”<<endl; Test second(2); second object invokes cout<<“ (local automatic created in main)”<<endl; its constructor static Test third(3); third object invokes cout<<“ (local static created in main)”<<endl; its constructor func(); // function func is invoked, refer to slide 16 forth object invokes { Test forth(4); its constructor cout<<“ (local automatic crated in inner block inmain)”<<endl; } func(); //function func is invoked again 36/15}
  • 37. Global, Static and Local Objectsvoid func() fifth object invokes{ Test fifth(5); its constructor cout<<“ (local automatic created in func)”<<endl; static Test sixth(3); sixth object DOESN’T invok cout<<“ (local static created in func)”<<endl; its constructor again} fifth object invokes its destructor 37/15
  • 38. Global, Static and Local ObjectsOutput:Object 1 constructor (global created before main)Object 2 constructor (local automatic created in main)Object 3 constructor (local static created in main)Object 5 constructor (local automatic created in func)Object 6 constructor (local static created in func)Object 5 destructorObject 4 constructor (local automatic created in inner block in main)Object 4 destructorObject 5 constructor (local automatic created in func) (local static created in func)Object 5 destructorObject 2 destructorObject 6 destructorObject 3 destructorObject 1 destructor 38/15

×