• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Classes, objects and methods
 

Classes, objects and methods

on

  • 2,980 views

 

Statistics

Views

Total Views
2,980
Views on SlideShare
2,979
Embed Views
1

Actions

Likes
3
Downloads
1,135
Comments
2

1 Embed 1

http://jkwp.itsligo.ie 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

12 of 2 previous next

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • yah its too good
    Are you sure you want to
    Your message goes here
    Processing…
  • no
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Classes, objects and methods Classes, objects and methods Presentation Transcript

    • 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; Please 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; &quot;;
      • cout << abs(-11.0) << &quot; &quot;;
      • return 0;
      • }
      • int abs(int i)
      • {
      • cout << &quot;Using integer abs() &quot;;
      • return i<0 ? -i : i;
      • }
      double abs(double d) { cout << &quot;Using double abs() &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 << “ Length : “<<len <<“ ”; }
      • 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