classes, objects and methods

47
Lecture slides by: Farhan Amjad A new paradigm of programming

Upload: farhan-amjad

Post on 06-May-2015

3.804 views

Category:

Education


3 download

TRANSCRIPT

Page 1: Classes, objects and methods

Lecture slides by:

Farhan AmjadA new paradigm of programming

Page 2: Classes, objects and methods

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.

Page 3: Classes, objects and methods

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.

Page 4: Classes, objects and methods

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.

Page 5: Classes, objects and methods

SimilaritiesBoth are derived types. Both present similar featuresBoth are automatic typedefs

Class private members by default

Structurepublic members by defaultThe data members are thus accessible out of the structure

implementation

Classes are more advanced than structures

Page 6: Classes, objects and methods

Class

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).

data1data2data3

functiona()functionb()functionc()

Page 7: Classes, objects and methods

class welcome {

public: // access specifier

void display(){

cout<<“welcome to OOP class”;

} };

void main (){

welcome w1;

w1.display();

} Output: welcome to OOP class;

1. Forgetting the semicolon at the end of a class definition is a syntax error.

2. Defining a function inside another function is a syntax error.

Page 8: Classes, objects and methods

class welcome {

public:

void display(string course){

cout<<“welcome to the class of ”<<course;

} };

void main (){

String Coursename;

welcome w1;

cout << "Please enter the course name:" << endl;

Cin>>nameOfCourse ;

w1.display(Coursename);

}

Page 9: Classes, objects and methods

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 << "\nPlease enter the course name:“;Cin>> course;W1..setCourseName( Course );Cout<<“Course name of W1 is: “<<w1.getCourseName();w1.display();

}

Page 10: Classes, objects and methods

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();

}

Page 11: Classes, objects and methods

Class data member cannot be initialized at declaration time.

By default all data members have garbage value.

Page 12: Classes, objects and methods

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).

Page 13: Classes, objects and methods

Private Classprivate:

public:

data1data2

functiond()

functiona()functionb()functionc()

private part of class canbe accessed by memberfunctions of the sameclass only

public part of class constitutesthe interface that can be usedby other parts of the program

typically member data is privatewhereas member functions aremostly public

Page 14: Classes, objects and methods

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

Page 15: Classes, objects and methods

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

Page 16: Classes, objects and methods

:: 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;}

Page 17: Classes, objects and methods

#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){ ….}

Page 18: Classes, objects and methods

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}

Page 19: Classes, objects and methods

object d1data:

functions:

d=15;m=3;y=2001;

object d2data:

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();

Page 20: Classes, objects and methods

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 d1d1.init(12,3,2001); // call member function init for d1init(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.

Page 21: Classes, objects and methods

◆ 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.

Page 22: Classes, objects and methods

#inclule……………….

int abs(int );

double abs(double );

int main()

{

cout << abs(-10) << "\n";

cout << abs(-11.0) << "\n";

return 0;

}

int abs(int i)

{

cout << "Using integer abs()\n";

return i<0 ? -i : i;

}

double abs(double d){cout << "Using double abs()\n";return d<0.0 ? -d : d;}

Page 23: Classes, objects and methods

#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; };

Page 24: Classes, objects and methods

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);

Page 25: Classes, objects and methods

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};

Page 26: Classes, objects and methods

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.

Page 27: Classes, objects and methods

class Date{public: Date(); // constructor for class Dateprivate: 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};

Page 28: Classes, objects and methods

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;}

Page 29: Classes, objects and methods

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;

};

Page 30: Classes, objects and methods

#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());

}

Page 31: Classes, objects and methods

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

}

Page 32: Classes, objects and methods

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

Page 33: Classes, objects and methods

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

}

Page 34: Classes, objects and methods

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}

Page 35: Classes, objects and methods

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;

}

Page 36: Classes, objects and methods

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.2000Date d1(14,5,2000);Date d2(10,4,2000);cout << d1.diff(d2) << endl; // difference between d1 and d2

Page 37: Classes, objects and methods

object d2

daymonthyear

object d1

daymonthyear

d2.add_days(d1,65);

day d1.day

Member function of d2 refers to its own data member day directly

Member function of d2 refersto data member day in objectd1 using the dot operator

Page 38: Classes, objects and methods

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

Page 39: Classes, objects and methods

A member function that is declared as constant does not modify the data of the objectclass 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; }

Page 40: Classes, objects and methods

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

}

Page 41: Classes, objects and methods

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

Page 42: Classes, objects and methods

Class Date{private: static int counter=0; int day, month, year; public: Date() { counter++; } ~Date() { counter--; } void display() { cout << ”There are ” << counter << ” Foo objects!”; }};

Page 43: Classes, objects and methods

Date f1, Date f2;

f1.display(); // 2 foo objects

Date f3;

f1.display(); // 3 foo objects

// f3 gets destroyed

f1.display(); // 2 foo objects

Page 44: Classes, objects and methods

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 };

};

Page 45: Classes, objects and methods

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;}

Page 46: Classes, objects and methods

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(); }

Page 47: Classes, objects and methods

Deitel & Deitel: chapters 3, 8 Stroustrup: chapters 10 Lafore : chapters 6 Lippman : chapters 13, 14 D.S.Malik: chapter 6, 8