SlideShare a Scribd company logo
Lecture slides by:   Farhan Amjad A new paradigm of programming
What classes, objects, member functions and data members are. How to define a class and use it to create an object. How to define member functions in a class to implement the class's behaviors. How to declare data members in a class to implement the class's attributes. How to call a member function of an object to make that member function perform its task. The differences between data members of a class and local variables of a function. How to use a constructor to ensure that an object's data is initialized when the object is created. How to engineer a class to separate its interface from its implementation and encourage reuse.
A  CLASS  is a grouping of data and functions. A class is very much like a structure type as used in C language. It is only a pattern (a template) to be used to create a variable which can be manipulated in a program.  A class is a description of similar objects. Classes are designed to give certain services.  An  OBJECT  is an instance of a class, which is similar to a variable defined as an instance of a type. An object is what you actually use in a program.  Objects are instances of classes An  ATTRIBUTE  is a data member of a class that can take different values for different instances (objects) of this class. Example: Name of a student.
A  method (member function)  is a function contained within the class. You will find the functions used within class often referred to as methods in programming literature. A  message  is the same thing as a function call. In object oriented programming. We send messages instead of calling functions. For the time being you can think of them as identical.  Messages are sent to objects to get some services from them.
Similarities Both are  derived   types.  Both present similar features Both are automatic   typedefs Class  private members by default Structure public members by default The data members are thus accessible out of the structure implementation Classes are more advanced than structures
A class is a user-defined prototype from which one can  instantiate  objects of a particular type in the same way one generates integer variables using the built-in data type int. A class contains data (member data) and functions (membership functions). Class data1 data2 data3 functiona() functionb() functionc()
class welcome { public: //   access specifier void display(){ cout<<“welcome to OOP class”; }  }; void main (){ welcome w1; w1.display(); } Output: welcome to OOP class ; Forgetting the semicolon at the end of a class definition is a syntax error. Defining a function inside another function is a syntax error.
class welcome { public: void display(string course){ cout<<“welcome to the class of ”<<course; }  }; void main (){ String Coursename;  welcome w1; cout << &quot;Please enter the course name:&quot; << endl;  Cin>>nameOfCourse ;  w1.display(Coursename); }
class welcome { private:   string courseName;   public: void setCourseName( string name )  {  courseName = name; } string getCourseName()  {  return courseName; }  void display(string course){ cout<<“welcome to the class of ”<<getCourseName() ; } }; void main (){ String Course;  welcome w1; cout << &quot;\nPlease enter the course name:“; Cin>> course; W1..setCourseName( Course ); Cout<<“Course name of W1 is:  “<<w1.getCourseName(); w1.display(); }
Class smallobj{ private: int somedata; Public: void setdata (int d){ somedata=d;   } Void showdata(){ cout<<“Data is……”<<somedata } Void main() {Smallobj s1, s2; S1.setdata(23);  S2.setdata(54); S1.showdata(); S2.showdata(); }
Class data member  cannot be initialized at declaration time. By default all data members have garbage value.
class Date    // declares class name { private:   // not visible outside the class int day, month, year;  // member data public:   // visible interface void init(int d, int m, int y);  // initialize date void add_year(int n);  // add n years void add_month(int n);  // add n months void add_day(int n);  // add n days void show_date();  // displays date };  // do not forget the ; here !!! In our example first data and then functions are written, it is also possible to write in reverse order. Data and functions of the class are called members of the class. In our class body of the function is written outside of the class, if it is written inside the class then it is called  inline function (macro) .
Private Class private:  public:  data1 data2 functiond() functiona() functionb() functionc() private part of class can be accessed by member functions of the same class only public part of class constitutes the interface that can be used by other parts of the program typically member data is private whereas member functions are mostly public
Data hiding  is mechanism to protect data from accidentally or deliberately being manipulated from other parts of the program The primary mechanism for  data hiding  is to put it in a class and make it private. Private data can only be accessed from within the class Public data or functions are accessible from outside the class
Binary scope resolution operator ( :: ) Specifies which class owns the member function  Different classes can have the same name for member functions Format for definition class member functions ReturnType ClassName :: MemberFunctionName( ){ … } If member function is defined  inside  the class Scope resolution operator and class name are not needed
:: scope resulution operator  void Date::init(int d, int m, int y) { day=d; month=m; year = y; } void Date::add_month(int n) { month+=n; year+= (month)/12; }
#include <iostream.h> void Date::show_date()  // Date:: specifies that show_date is a // member function of class Date { cout << d << ”.” << m << ”.” << y << endl; } void Date::add_year(int n) { year+=y; } void Date::add_day(int n) { … . }
class Date  // class definition { … }; void main () { Date d1;  // instantiate  a variable/object d1 of class Date Date d2;  // instantiate a second object d2 of class Date d1.init(15,3,2001);  // call member function init for object d1 d1.show_date();  // member function show_date for d1 d2.init(10,1,2000);  // call member function init for object d1 d2.show_date();  // member function show_date for d1 }
object d1 data:  functions:  d=15; m=3; y=2001; object d2 data:  function:  d=10; m=1; y=2000; void add_day(int n); void add_year(int n);  void show_date(); class Date void add_day(int n) { … } void add_year(int n) { … } void show_date() { … } void add_day(int n); void add_year(int n);  void show_date();
A class member function can only be called in  association with a specific object of that class using the dot operator (period)  Date d1;  // object of class d1 d1.init(12,3,2001);  //  call member function init for d1 init(13,2,2000);  // illegal, no object associated to call init A member function always operates on a specific object not the class itself. Each objects has its own data but objects of the same  class share the same member function code In other OO languages member function calls are also called  messages .
◆  Visibility: in structures, all members are by default visible to anyone. C++ however adds the ability to make the distinction between public and  non-public members. ◆  Levels of Visibility: ●  Public: members are visible to any function including member, nonmember and members of other ures. ●  Private: members are only visible to other member functions of the  ures. Data hiding (encapsulation), can prevent unanticipated modifications to the data members. ●  Protected: at this stage, the same as private. Members are available also to members of inheriting classes. ◆  In structures by  default visibility is  public  and in classes default visibility is  private.
#inclule………………. int abs(int ); double abs(double ); int main() { cout << abs(-10) << &quot;\n&quot;; cout << abs(-11.0) << &quot;\n&quot;; return 0; } int abs(int i) { cout << &quot;Using integer abs()\n&quot;; return i<0 ? -i : i; } double abs(double d) { cout << &quot;Using double abs()\n&quot;; return d<0.0 ? -d : d; }
#include <string.h> #include<iostream.h> Class String { public: void assign (char* st) { Strcpy (s, st); Len = strlen(st); } int length () { return len; } Void print() { cout<<s << “\n Length : “<<len <<“\n”; } Private: maxLen = 222; Char s[maxLen]; Int len; };
String s1, s2, s3,s4; Cin>>s2>>s3; S3=“welcome”+s2; S4=s1+s2; S3=s1+ “  “ + s2; S4= “Hello” + “there!”  //illegal Cout<<s1.length();  n=s1.length(); S1= “Hi dear how r u?” S1.find(“hi”);  s1.find(s2); S4=s21.substr(0,5); S2.swap(s1);
A constructor is a member function that is automatically invoked when a new object of a class is instantiated.  The constructor must always have the same name as the class and has no return type. class Date { Date();  // constructor for class Date };
Constructor Special member function that initializes data members of a class object Constructors cannot return values Same name as the class Declarations Once class defined, can be used as a data type Time sunset,  // object of type Time   arrayOfTimes[ 5 ],  // array of Time objects   *pointerToTime,  // pointer to a Time object   &dinnerTime = sunset;  // reference to a Time object Note: The class name becomes the new type specifier.
class Date { public: Date();  // constructor for class Date private: int day; int month; int year; }; Date::Date() : day(1), month(1), year(1900) // initialize int day with 1, int month with 1 etc. { //empty body };
two types of member initialization in class constructor by initialization : members are initialized before the constructor is executed (necessary for data members tha have no default constructor)  by assignment : members are created per default constructor first and then a value is assigned to them Date::Date(int d, int m, int y) : day(d), month(m), year(y) { } Date::Date(int d, int m, int y)  // assignment initialization  { day=d; month=m; year=y; }
class Date { public: Date();  // default constructor with standard date 1.1.1900 Date(int d, int m, int y);  // constructor with day, month, year Date(string date);  // constructor with string private: int day; int month; int year; };
#include <stdlib> #include <string> Date::Date(int d, int m, int y)  : day(d), month(m), year(y) { } Date::Date(string str) // constructor with string dd.mm.yyyy { day=atoi(str.substr(0,2).c_str()); month=atoi(str.substr(3,2).c_str()); year=atoi(str.substr(6,4).c_str()); }
void main() { Date d1; // default constructor  date 1.1.1900 Date d2(12,9,1999);  // Date(int d, int m, int y) constructor  Date d3(”17.2.1998”); // Date(string date) constructor }
Destructors are automatically called when an object is destroyed The most common use for destructors is to deallocate memory  class Date { public: Date();  // constructor ~Date();  // destructor  … }; if … {  Date d1; … } // destructor for d1 is invoked
class Date { public: Date(int d=1, int m=1, int y=1900);  // constructor with  // day, month, year and default values }; Date::Date(int d, int m, int y) : day(d), month(m), year(y) {} void main() { Date d1;  // 1.1.1900 Date d2(5);  //  5.1.1900 Date d3(15,8); // 15.8.1900 Date d4(12,10,1998); // 12.10.1998 }
The copy constructor initializes on object with another object of the same class. Each class possesses a built-in  default copy constructor  which is a one-argument constructor which argument is an object of the same class The default copy constructor can be overloaded by explicitly defining a constructor Date(Date& d) void main() { Date d1(12,4,1997); Date d2(d1);  // default copy constructor Date d3=d1;  // also default copy constructor }
Class objects can become arguments to functions in the same way as ordinary built-in data type parameters class Date { int diff(Date d);  // computes the number of days between two dates }; int Date::diff(Date d) { int n=day-d.day;  // d.day access member data day of object d n+= 30 * (month – d.month);  // approximately correct… n+= 365 (year – d.year);  return n; }
class Date { void add_days (Date d, int n);  // computes the date d + n days  }; void Date::add_days(Date d, int n)  { day=d.day + n % 30;  month = d.month + (n % 365) / 30; year = d.year + n / 365; } }; Int main(){  Date d1(14,5,2000); Date d2; d2.add_days(d1,65);  // d2 set to 29.7.2000 Date d1(14,5,2000); Date d2(10,4,2000); cout << d1.diff(d2) << endl;  // difference between d1 and d2
object d2  day month year object d1  day month year d2.add_days(d1,65); day d1.day Member function of d2  refers  to its own data member day  directly  Member function of d2 refers to data member day in object d1 using the dot operator
class Date { Date get_date (int n);  // returns the date + n days  }; Date Date::get_date(Date n)  { Date temp; temp.day=day +n.day; temp.month = month + n.month; temp.year = year + n.year; return temp; } Main(){ Date d1(14,5,2000); Date d3; Date d2=d1.get_date(d3);  // d2 set to 29.7.2000
A member function that is declared as constant does not modify the data of the object class Date { int year() const;  // const year() does not modify data  void add_year(int n);  // non-const add_year() modifies data }; int Date::year() const  // defined as const { return year; } int Date::add_year(int n)  { year+=n; }
A const member function can be invoked for const and non-const objects, whereas a non-const member function can only be invoked for non-const objects void f(Date &d, const Date &cd)  { int i=d.year();  // ok d.add_year(2);  // ok int j=cd.year();  // ok  cd.add_year(3);  // error cannot change const object cd }
Normally each object possesses its own separate data members  A static data member is similar to a normal static variable and is shared among all objects of the same class There is exactly one copy of a static data member rather than one copy per object as for non-static variables
Class Date { private: static int counter=0; int day, month, year; public: Date() { counter++; } ~Date() { counter--; } void display()  { cout << ”There are ” << counter << ” Foo objects!”; } };
Date f1,  Date f2; f1.display();  // 2 foo objects  Date f3; f1.display();  // 3 foo objects // f3 gets destroyed f1.display();  // 2 foo objects
class Date { int days_per_month();  int days_per_year(); bool leap_year(); static int days_in_month[12] =  { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; };
bool Date::leap_year() {  return ((( year % 4  == 0)  && (year % 100 != 0)) || (year % 400 == 0));  } int Date::days_per_month() {  if ((month==2) && leap_year()) return 29; else return days_in_month[month-1];  } int Date::days_per_year() {  If leap_year() return 366; else return 365; }
Class student { String name; int Reg; int marks; Student(){ } Void print() { cout<<name<<reg<<marks;} }; main() { Student s[16]; S[3].name= “Awae hi”;  cout<< S[3].print();  }
Deitel & Deitel: chapters 3, 8 Stroustrup: chapters 10 Lafore : chapters 6 Lippman : chapters 13, 14 D.S.Malik: chapter 6, 8
Ad

More Related Content

What's hot (20)

4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
Praveen M Jigajinni
 
Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.
Enam Khan
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
NainaKhan28
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
 
OOP C++
OOP C++OOP C++
OOP C++
Ahmed Farag
 
Lecture 2 (1)
Lecture 2 (1)Lecture 2 (1)
Lecture 2 (1)
zahid khan
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Unit v(dsc++)
Unit v(dsc++)Unit v(dsc++)
Unit v(dsc++)
Durga Devi
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
Vishnu Shaji
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++
ThamizhselviKrishnam
 
Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3
C# Learning Classes
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
VasanthiMuniasamy2
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
Swarup Kumar Boro
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.
Enam Khan
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
NainaKhan28
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
Vishnu Shaji
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++
ThamizhselviKrishnam
 
Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3
C# Learning Classes
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
Swarup Kumar Boro
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 

Viewers also liked (11)

Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
Atul Sehdev
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in java
Atul Sehdev
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
রাকিন রাকিন
 
Data types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in javaData types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
rahulsahay19
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
Abhilash Nair
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
Atul Sehdev
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in java
Atul Sehdev
 
Data types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in javaData types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
rahulsahay19
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
Abhilash Nair
 
Ad

Similar to Classes, objects and methods (20)

oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
Atif Khan
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
rumanatasnim415
 
Class and object
Class and objectClass and object
Class and object
prabhat kumar
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
Dr. SURBHI SAROHA
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
nafisa rahman
 
classes data type for Btech students.ppt
classes data type for Btech students.pptclasses data type for Btech students.ppt
classes data type for Btech students.ppt
soniasharmafdp
 
C++ Notes
C++ NotesC++ Notes
C++ Notes
MOHAMED RIYAZUDEEN
 
Classes in C++ computer language presentation.ppt
Classes in C++ computer language presentation.pptClasses in C++ computer language presentation.ppt
Classes in C++ computer language presentation.ppt
AjayLobo1
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
secondakay
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
Mohammed Saleh
 
C++ Presen. tation.pptx
C++ Presen.                   tation.pptxC++ Presen.                   tation.pptx
C++ Presen. tation.pptx
mohitsinha7739289047
 
ccc
cccccc
ccc
Zainab Irshad
 
My c++
My c++My c++
My c++
snathick
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdf
study material
 
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
Unit_2_oop By Alfiya Sayyed Maam from  AIARKPUnit_2_oop By Alfiya Sayyed Maam from  AIARKP
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
mradeen946
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
Dennis Chang
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
Class object
Class objectClass object
Class object
Dr. Anand Bihari
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
Atif Khan
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
nafisa rahman
 
classes data type for Btech students.ppt
classes data type for Btech students.pptclasses data type for Btech students.ppt
classes data type for Btech students.ppt
soniasharmafdp
 
Classes in C++ computer language presentation.ppt
Classes in C++ computer language presentation.pptClasses in C++ computer language presentation.ppt
Classes in C++ computer language presentation.ppt
AjayLobo1
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
secondakay
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdf
study material
 
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
Unit_2_oop By Alfiya Sayyed Maam from  AIARKPUnit_2_oop By Alfiya Sayyed Maam from  AIARKP
Unit_2_oop By Alfiya Sayyed Maam from AIARKP
mradeen946
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
Dennis Chang
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
Ad

More from farhan amjad (6)

Views and security
Views and securityViews and security
Views and security
farhan amjad
 
Views and security
Views and securityViews and security
Views and security
farhan amjad
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
farhan amjad
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
farhan amjad
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
farhan amjad
 
Views and security
Views and securityViews and security
Views and security
farhan amjad
 
Views and security
Views and securityViews and security
Views and security
farhan amjad
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
farhan amjad
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
farhan amjad
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
farhan amjad
 

Recently uploaded (20)

Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 

Classes, objects and methods

  • 1. Lecture slides by: Farhan Amjad A new paradigm of programming
  • 2. What classes, objects, member functions and data members are. How to define a class and use it to create an object. How to define member functions in a class to implement the class's behaviors. How to declare data members in a class to implement the class's attributes. How to call a member function of an object to make that member function perform its task. The differences between data members of a class and local variables of a function. How to use a constructor to ensure that an object's data is initialized when the object is created. How to engineer a class to separate its interface from its implementation and encourage reuse.
  • 3. A CLASS is a grouping of data and functions. A class is very much like a structure type as used in C language. It is only a pattern (a template) to be used to create a variable which can be manipulated in a program. A class is a description of similar objects. Classes are designed to give certain services. An OBJECT is an instance of a class, which is similar to a variable defined as an instance of a type. An object is what you actually use in a program. Objects are instances of classes An ATTRIBUTE is a data member of a class that can take different values for different instances (objects) of this class. Example: Name of a student.
  • 4. A method (member function) is a function contained within the class. You will find the functions used within class often referred to as methods in programming literature. A message is the same thing as a function call. In object oriented programming. We send messages instead of calling functions. For the time being you can think of them as identical. Messages are sent to objects to get some services from them.
  • 5. Similarities Both are derived types. Both present similar features Both are automatic typedefs Class private members by default Structure public members by default The data members are thus accessible out of the structure implementation Classes are more advanced than structures
  • 6. A class is a user-defined prototype from which one can instantiate objects of a particular type in the same way one generates integer variables using the built-in data type int. A class contains data (member data) and functions (membership functions). Class data1 data2 data3 functiona() functionb() functionc()
  • 7. class welcome { public: // access specifier void display(){ cout<<“welcome to OOP class”; } }; void main (){ welcome w1; w1.display(); } Output: welcome to OOP class ; Forgetting the semicolon at the end of a class definition is a syntax error. Defining a function inside another function is a syntax error.
  • 8. class welcome { public: void display(string course){ cout<<“welcome to the class of ”<<course; } }; void main (){ String Coursename; welcome w1; cout << &quot;Please enter the course name:&quot; << endl; Cin>>nameOfCourse ; w1.display(Coursename); }
  • 9. class welcome { private: string courseName; public: void setCourseName( string name ) { courseName = name; } string getCourseName() { return courseName; } void display(string course){ cout<<“welcome to the class of ”<<getCourseName() ; } }; void main (){ String Course; welcome w1; cout << &quot;\nPlease enter the course name:“; Cin>> course; W1..setCourseName( Course ); Cout<<“Course name of W1 is: “<<w1.getCourseName(); w1.display(); }
  • 10. Class smallobj{ private: int somedata; Public: void setdata (int d){ somedata=d; } Void showdata(){ cout<<“Data is……”<<somedata } Void main() {Smallobj s1, s2; S1.setdata(23); S2.setdata(54); S1.showdata(); S2.showdata(); }
  • 11. Class data member cannot be initialized at declaration time. By default all data members have garbage value.
  • 12. class Date // declares class name { private: // not visible outside the class int day, month, year; // member data public: // visible interface void init(int d, int m, int y); // initialize date void add_year(int n); // add n years void add_month(int n); // add n months void add_day(int n); // add n days void show_date(); // displays date }; // do not forget the ; here !!! In our example first data and then functions are written, it is also possible to write in reverse order. Data and functions of the class are called members of the class. In our class body of the function is written outside of the class, if it is written inside the class then it is called inline function (macro) .
  • 13. Private Class private: public: data1 data2 functiond() functiona() functionb() functionc() private part of class can be accessed by member functions of the same class only public part of class constitutes the interface that can be used by other parts of the program typically member data is private whereas member functions are mostly public
  • 14. Data hiding is mechanism to protect data from accidentally or deliberately being manipulated from other parts of the program The primary mechanism for data hiding is to put it in a class and make it private. Private data can only be accessed from within the class Public data or functions are accessible from outside the class
  • 15. Binary scope resolution operator ( :: ) Specifies which class owns the member function Different classes can have the same name for member functions Format for definition class member functions ReturnType ClassName :: MemberFunctionName( ){ … } If member function is defined inside the class Scope resolution operator and class name are not needed
  • 16. :: scope resulution operator void Date::init(int d, int m, int y) { day=d; month=m; year = y; } void Date::add_month(int n) { month+=n; year+= (month)/12; }
  • 17. #include <iostream.h> void Date::show_date() // Date:: specifies that show_date is a // member function of class Date { cout << d << ”.” << m << ”.” << y << endl; } void Date::add_year(int n) { year+=y; } void Date::add_day(int n) { … . }
  • 18. class Date // class definition { … }; void main () { Date d1; // instantiate a variable/object d1 of class Date Date d2; // instantiate a second object d2 of class Date d1.init(15,3,2001); // call member function init for object d1 d1.show_date(); // member function show_date for d1 d2.init(10,1,2000); // call member function init for object d1 d2.show_date(); // member function show_date for d1 }
  • 19. object d1 data: functions: d=15; m=3; y=2001; object d2 data: function: d=10; m=1; y=2000; void add_day(int n); void add_year(int n); void show_date(); class Date void add_day(int n) { … } void add_year(int n) { … } void show_date() { … } void add_day(int n); void add_year(int n); void show_date();
  • 20. A class member function can only be called in association with a specific object of that class using the dot operator (period) Date d1; // object of class d1 d1.init(12,3,2001); // call member function init for d1 init(13,2,2000); // illegal, no object associated to call init A member function always operates on a specific object not the class itself. Each objects has its own data but objects of the same class share the same member function code In other OO languages member function calls are also called messages .
  • 21. ◆ Visibility: in structures, all members are by default visible to anyone. C++ however adds the ability to make the distinction between public and non-public members. ◆ Levels of Visibility: ● Public: members are visible to any function including member, nonmember and members of other ures. ● Private: members are only visible to other member functions of the ures. Data hiding (encapsulation), can prevent unanticipated modifications to the data members. ● Protected: at this stage, the same as private. Members are available also to members of inheriting classes. ◆ In structures by default visibility is public and in classes default visibility is private.
  • 22. #inclule………………. int abs(int ); double abs(double ); int main() { cout << abs(-10) << &quot;\n&quot;; cout << abs(-11.0) << &quot;\n&quot;; return 0; } int abs(int i) { cout << &quot;Using integer abs()\n&quot;; return i<0 ? -i : i; } double abs(double d) { cout << &quot;Using double abs()\n&quot;; return d<0.0 ? -d : d; }
  • 23. #include <string.h> #include<iostream.h> Class String { public: void assign (char* st) { Strcpy (s, st); Len = strlen(st); } int length () { return len; } Void print() { cout<<s << “\n Length : “<<len <<“\n”; } Private: maxLen = 222; Char s[maxLen]; Int len; };
  • 24. String s1, s2, s3,s4; Cin>>s2>>s3; S3=“welcome”+s2; S4=s1+s2; S3=s1+ “ “ + s2; S4= “Hello” + “there!” //illegal Cout<<s1.length(); n=s1.length(); S1= “Hi dear how r u?” S1.find(“hi”); s1.find(s2); S4=s21.substr(0,5); S2.swap(s1);
  • 25. A constructor is a member function that is automatically invoked when a new object of a class is instantiated. The constructor must always have the same name as the class and has no return type. class Date { Date(); // constructor for class Date };
  • 26. Constructor Special member function that initializes data members of a class object Constructors cannot return values Same name as the class Declarations Once class defined, can be used as a data type Time sunset, // object of type Time arrayOfTimes[ 5 ], // array of Time objects *pointerToTime, // pointer to a Time object &dinnerTime = sunset; // reference to a Time object Note: The class name becomes the new type specifier.
  • 27. class Date { public: Date(); // constructor for class Date private: int day; int month; int year; }; Date::Date() : day(1), month(1), year(1900) // initialize int day with 1, int month with 1 etc. { //empty body };
  • 28. two types of member initialization in class constructor by initialization : members are initialized before the constructor is executed (necessary for data members tha have no default constructor) by assignment : members are created per default constructor first and then a value is assigned to them Date::Date(int d, int m, int y) : day(d), month(m), year(y) { } Date::Date(int d, int m, int y) // assignment initialization { day=d; month=m; year=y; }
  • 29. class Date { public: Date(); // default constructor with standard date 1.1.1900 Date(int d, int m, int y); // constructor with day, month, year Date(string date); // constructor with string private: int day; int month; int year; };
  • 30. #include <stdlib> #include <string> Date::Date(int d, int m, int y) : day(d), month(m), year(y) { } Date::Date(string str) // constructor with string dd.mm.yyyy { day=atoi(str.substr(0,2).c_str()); month=atoi(str.substr(3,2).c_str()); year=atoi(str.substr(6,4).c_str()); }
  • 31. void main() { Date d1; // default constructor date 1.1.1900 Date d2(12,9,1999); // Date(int d, int m, int y) constructor Date d3(”17.2.1998”); // Date(string date) constructor }
  • 32. Destructors are automatically called when an object is destroyed The most common use for destructors is to deallocate memory class Date { public: Date(); // constructor ~Date(); // destructor … }; if … { Date d1; … } // destructor for d1 is invoked
  • 33. class Date { public: Date(int d=1, int m=1, int y=1900); // constructor with // day, month, year and default values }; Date::Date(int d, int m, int y) : day(d), month(m), year(y) {} void main() { Date d1; // 1.1.1900 Date d2(5); // 5.1.1900 Date d3(15,8); // 15.8.1900 Date d4(12,10,1998); // 12.10.1998 }
  • 34. The copy constructor initializes on object with another object of the same class. Each class possesses a built-in default copy constructor which is a one-argument constructor which argument is an object of the same class The default copy constructor can be overloaded by explicitly defining a constructor Date(Date& d) void main() { Date d1(12,4,1997); Date d2(d1); // default copy constructor Date d3=d1; // also default copy constructor }
  • 35. Class objects can become arguments to functions in the same way as ordinary built-in data type parameters class Date { int diff(Date d); // computes the number of days between two dates }; int Date::diff(Date d) { int n=day-d.day; // d.day access member data day of object d n+= 30 * (month – d.month); // approximately correct… n+= 365 (year – d.year); return n; }
  • 36. class Date { void add_days (Date d, int n); // computes the date d + n days }; void Date::add_days(Date d, int n) { day=d.day + n % 30; month = d.month + (n % 365) / 30; year = d.year + n / 365; } }; Int main(){ Date d1(14,5,2000); Date d2; d2.add_days(d1,65); // d2 set to 29.7.2000 Date d1(14,5,2000); Date d2(10,4,2000); cout << d1.diff(d2) << endl; // difference between d1 and d2
  • 37. object d2 day month year object d1 day month year d2.add_days(d1,65); day d1.day Member function of d2 refers to its own data member day directly Member function of d2 refers to data member day in object d1 using the dot operator
  • 38. class Date { Date get_date (int n); // returns the date + n days }; Date Date::get_date(Date n) { Date temp; temp.day=day +n.day; temp.month = month + n.month; temp.year = year + n.year; return temp; } Main(){ Date d1(14,5,2000); Date d3; Date d2=d1.get_date(d3); // d2 set to 29.7.2000
  • 39. A member function that is declared as constant does not modify the data of the object class Date { int year() const; // const year() does not modify data void add_year(int n); // non-const add_year() modifies data }; int Date::year() const // defined as const { return year; } int Date::add_year(int n) { year+=n; }
  • 40. A const member function can be invoked for const and non-const objects, whereas a non-const member function can only be invoked for non-const objects void f(Date &d, const Date &cd) { int i=d.year(); // ok d.add_year(2); // ok int j=cd.year(); // ok cd.add_year(3); // error cannot change const object cd }
  • 41. Normally each object possesses its own separate data members A static data member is similar to a normal static variable and is shared among all objects of the same class There is exactly one copy of a static data member rather than one copy per object as for non-static variables
  • 42. Class Date { private: static int counter=0; int day, month, year; public: Date() { counter++; } ~Date() { counter--; } void display() { cout << ”There are ” << counter << ” Foo objects!”; } };
  • 43. Date f1, Date f2; f1.display(); // 2 foo objects Date f3; f1.display(); // 3 foo objects // f3 gets destroyed f1.display(); // 2 foo objects
  • 44. class Date { int days_per_month(); int days_per_year(); bool leap_year(); static int days_in_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; };
  • 45. bool Date::leap_year() { return ((( year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)); } int Date::days_per_month() { if ((month==2) && leap_year()) return 29; else return days_in_month[month-1]; } int Date::days_per_year() { If leap_year() return 366; else return 365; }
  • 46. Class student { String name; int Reg; int marks; Student(){ } Void print() { cout<<name<<reg<<marks;} }; main() { Student s[16]; S[3].name= “Awae hi”; cout<< S[3].print(); }
  • 47. Deitel & Deitel: chapters 3, 8 Stroustrup: chapters 10 Lafore : chapters 6 Lippman : chapters 13, 14 D.S.Malik: chapter 6, 8
  翻译: