Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions...

60

Transcript of Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions...

Page 1: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.
Page 2: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

IntroductionObject-oriented programming (OOP)

Encapsulates data (attributes) and functions (behavior) into packages called classes

Information hiding Class objects communicate across well-defined

interfacesImplementation details hidden within classes

themselvesUser-defined (programmer-defined) types: classes

Data (data members) Functions (member functions or methods)Similar to blueprints – reusableClass instance: object

2

Page 3: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Introduction (Cont.)Classes

Model objects Attributes (data members) Behaviors (member functions)

Defined using keyword classMember functions

Methods Invoked in response to messages

Member access specifierspublic:

Accessible wherever object of class in scopeprivate:

Accessible only to member functions of classprotected:

3

Page 4: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Class constructorA function with the same name as the class.Used to create an instance of a class (object)

and initialize the data members of the object.A constructor function is called automatically

when an object of that class is created.A constructor can not have a return value.

Page 5: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Class constructor (Cont ..)If you do not declare a constructor for a

class, one will be declared for you automatically.This constructor will have no arguments.

A constructor with no argument (or with all arguments with default values) is called a default constructor.

Page 6: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Multiple constructorsA single class can have more than one

constructor.The compiler chooses which constructor to

invoke by the signature of the constructor (the number and type of arguments).If no arguments are given, the default

constructor is used.

Page 7: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(); Foo(int j, float x, string s); Foo(int j, string s); Foo(int k, string s, int j); ...};

// which constructor will be called?

Foo obj1;Foo obj2(2, "Happy");Foo obj3(4, "Joe", 0);Foo obj4(5, 4.3, "Joe");

Page 8: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Constructor with default argument valuesDefault values for constructor arguments may

be assigned in the constructor prototype.If no argument value is provided in the class

object declaration, the default value is used.

Page 9: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(int j=0, float x=3.14, string s="Hello"); ...};...

// what happens?

Foo obj1;Foo obj2(1);Foo obj3(1, 2.5);Foo obj4(1, 2.5, "Joe");

Page 10: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(); Foo(int j=0, float x=3.14, string s="a"); ...};

...Foo obj1; // which constructor would be called?

Page 11: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(int i); Foo(int j=0, float x=3.14, string s="a"); ...};...// what happens?Foo obj1;Foo obj2(5);Foo obj3(5, 4.2);

Page 12: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: // No constructor provided ... private: float m; string city;};

...Foo obj1; // automatic constructor called // no initialization

Page 13: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Member initialization listMember data can be initialized by a

constructor in two waysCode inserted in the constructorA member initialization list

Member initialization listGiven in constructor definition (not prototype)Follows the argument list and consists of a colon

followed by a comma separated list of member name/argument pairs

Page 14: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(int, float); ... private: int k; float z;};

Foo::Foo(int a, float b): k(a), z(b){ // body of the constructor is often empty}

Foo obj1(5,15.0); // Instantiate an object

Page 15: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(int, float); ... private: int k; float z; string n;};

Foo::Foo(int a, float b): z(b), k(a){ n = "John Doe";}

Foo obj2(5, 15.0); // Instantiate an object

Page 16: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Class destructorA class object is usually destroyed when

program execution leaves the "scope" of the declaration.

Many times you will want to write code to specifically deallocate an object’s memory e.g., when dynamic memory allocation is used.

A special member function called destructor is used to accomplish this.

Page 17: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Class destructor (Cont ..)The destructor is called automatically when

the class object is destroyed.The name of the destructor function is the

class name preceded by a tilde (~).The destructor cannot have arguments.The destructor cannot return a value.An automatic destructor is defined if you do

not define one.

Page 18: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: ... ~Foo(); // destructor prototype private: ...};

Foo::~Foo( ) // destructor definition{ ... // code for destructor}

Page 19: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Designing a ClassData members normally placed in private:

section of a classFunction members usually in public: sectionTypically public: section followed by private:

although not required by compiler

19

Page 20: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Class LibrariesClass declarations placed in header file

Given .h extensionContains data items and prototypes

Implementation fileSame prefix name as header fileGiven .cpp extension

Programs which use this class library called client programs

20

Page 21: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Translating a Library

21

Page 22: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Constant member functions

Member functions can be made constant.Based on the Principle of least privilege

This means that they cannot change the value(s) of member data.

The keyword const should follow the argument list and must be used in both the prototype and definition of the member function.

Page 23: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: ... void Display() const; // prototype ... private: int a, b;};void Foo::Display() const // definition{ a = 10; // illegal code ...}

Page 24: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Constant objectsAn object can be declared as constant.The keyword const is used to specify that

the object cannot be modified. const Time noon(12,0,0);

Any attempt to modify a const object is a syntax error.

A const object must be initialized by constructor and cannot be modified once declared.

Page 25: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Const member dataMember data can be made constant by using

the keyword const in the class definition.Any const member data must be initialized

with an initialization list for the constructor.A const member data cannot be modified by

any function.

Page 26: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(int, float); ... private: const int k; float z;};

Foo::Foo(int a, float b): k(a), z(b){ k = a; // illegal code}

Page 27: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Assignment by default memberwise copy

• The assignment operator (=) can be used to assign an object to another object of the same type.

• Assignment is done by memberwise copy– Each member in one object is copied to

the same member of another object.– This type of copy should be done for

objects that only have value members.

Page 28: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Shallow CopyThe default member wise copy is called

shallow copy copies only the class data members and not

any pointed-to dataDone by default in three situations:

Assignment of one object into anotherPassing objects to functions by valueReturning an object from a function

Page 29: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Deep CopyA deep copy copies not only the class data

members, but also makes a separate stored copy of any pointed-to data at different locations than the original class object.

Page 30: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Copy ConstructorA constructor whose only argument is an

object of the same class.The copy constructor is implicitly called in 3

situations:passing object parameters by valueinitializing an object variable in its declarationreturning an object as the return value of a

function

Page 31: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Copy ConstructorEvery class has a default copy constructor

that uses a shallow copy.So when should you implement your own

copy constructor and how?

Page 32: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Test{ public: Test(float = 0, int = 0); Test(const Test &t); // copy constructor float GetMyFloat(); int GetMyInt(); void SetMyFloat(float); void SetMyInt(int); ~Test(); private: float myFloat; int *myInt;};

Page 33: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

ExampleTest::Test(float f, int i){ myFloat = f; myInt = new int; *myInt = i;}

Test::Test(const Test &t){ // complete the code}

Test::~Test(){ // complete the code}

Page 34: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleint main()

{

Test t1(10.5, 5);

Test t2 = t1; // copy constructor is called for t2

return 0;

}

Page 35: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Friend classesOne often uses several classes that work

together. Making the classes friends allows the classes

to access one another’s private member data.For class B to be a friend of class A, A must

explicitly declare B as a friend.Friendship is neither symmetric nor

transitive.

Page 36: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo1

{

friend class Foo2;

public:

...

private:

...

};

// This means Foo1 is granting friendship, i.e.

// access to private member data, to Foo2.

Page 37: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Friend FunctionsMaking a non-member function a friend of a

class allows that function to access private member data of a class.

To declare a non-member function as a friend of a class, precede the function prototype in the class definition with the word friend.

Page 38: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ friend void SetX(Foo &, int val); public: ... private: int x;};

//friend function definitionvoid SetX(Foo &f, int val){ f.x = val;}

Page 39: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Array of ObjectsJust like any built-in data type, a class type

can also be used to declare an array.To declare an array of class objects, the class

must have a default constructor .The default constructor is used to initialize

each object of the array since it is not possible to specify different constructors for each object.

Page 40: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Rational{ public: Rational (int n = 1, int d = 1); void Display(); private: int numerator, denominator;

};

Rational::Rational(int n, int d){ numerator = n; denominator = d;}

Rational r[10]; // creates an array of 10 objects // data members of each initialized to 1

Page 41: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

The this PointerEvery object has access to its own address

through a pointer called this.The this pointer is used implicitly to

reference both the data members and member functions of an object.

It can also be used explicitly.

Page 42: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Exampleclass Foo{ public: Foo(int x = 0); void Display() const; private: int x;};

void Foo::Display() const{ cout << this->x << endl; // cout << (*this).x << endl;}

Page 43: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Operator OverloadingAll unary and binary operators have pre-

defined implementations and are automatically available in expressions.

User defined implementations can also be introduced for these operators.

Operator overloading is the process of defining a new meaning for an existing operator.

Page 44: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Why overload operators?We can interact with instances of user-

defined class types by invoking member functions and for many classes, this notation may be cumbersome.

For some classes, it would be nice to be able to use operators with instances of these classes.

Page 45: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

ExampleSuppose we have a class for representing

time of the day (called Time) and two Time objects time1 and time2.

We want to be able to do things likecompare timesif (time1 < time2)

print times to an output streamcout << "The first time is " << time1;

Page 46: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

What to do?You have to define functions so that you are

able to overload any existing operators.These functions will implement the

overloaded operators.

Page 47: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

How to overload?An overloaded operator is nothing but a

function.The name of the function is the keyword operator followed by the symbol for the operator being overloaded.

Example: You will need a function called operator+ to overload the + operator.

Page 48: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Operators that can be overloaded

+ - * / % ^ & |

~ ! = < > += -= *=

/= %= ^= &= |= << >> >>=

<<= == != <= >= && || ++

-- ->* ‘ -> [ ] ( )

new delete new [ ] delete [ ]

Page 49: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Overloading is not automaticOverloading the operator + allows statements

like: object1 + object2

The above does not allow statements like: object1 += object2

The += operator must be overloaded separately.

Page 50: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

RestrictionsThe aritiy (number of operands) of the

operator cannot change.You cannot redefine the meaning of operators

when applied to built-in data types.You cannot define new operators, such as **.

Page 51: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Implementing operator overloadingThe functions must have access to the private

member data of the class.Two ways to write operator overloading

functions:Member functionsNon-member (friend) functions

Page 52: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Using member functionsIf the first operand of the operator is an object

(or a reference to an object) of the class type (for which we want to overload), the overloaded operator is typically implemented as a member function.

Member functions must be used for overloading: () [] -> =

Function prototypes for binary/unary operators:retType operator op(const Type &);retType operator op();

Page 53: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

ExampleSuppose we want to overload the * operator

for the Rational class so that we can write statements like: rObj = rObj1 * rObj2;

Required prototype:Rational operator*(const Rational &) const;

The previous statement will be translated by the compiler to: rObj = rObj1.operator*(rObj2);

Page 54: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

// the member function operator*()// will overload the * operator

class Rational{ public: Rational(int n = 0, int d = 1); Rational operator*(const Rational &) const; void Display() const; private: int numerator; int denominator;};

Page 55: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

// defining the operator*() function

Rational Rational::operator*(const Rational &r) const{ int n = (*this).numerator * r.numerator; // int n = numerator * r.numerator; int d = (*this).denominator * r.denominator; // int d = denominator * r.denominator; return Rational(n,d);}

Page 56: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Using friend functionsIf the first operand is not an object (or a

reference to an object) of the class type (for which we want to overload), the overloaded operator must be implemented as a non-member (friend) function.

Function prototypes for binary/unary operators:friend retType operator op(Type1 &, Type2 &);

friend retType operator op(Type &);

Page 57: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

ExampleWe often want to overload the insertion

(>>) and extraction (<<) operators so that objects can be read/written using these operators.

Suppose we want to be able to read and write rational numbers in format like 2/9.

I/O statements might look like: cin >> rObj; cout << rObj << endl;

Page 58: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

ExampleThe statement

cin >> rObj;

will be translated by the compiler to:

operator>>(cin,rObj);How will the compiler translate this one?

cout << rObj;

Page 59: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Example (Cont ..)class Rational{ friend ostream& operator<< (ostream&, const Rational&); friend istream& operator>> (istream&, Rational&);

public: Rational (int n = 0, int d = 1);

private: int numerator; int denominator;};

Page 60: Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding.

Example (Cont ..)ostream& operator<< (ostream &out, const Rational &r){ out << r.numerator << "/" << r.denominator; return out;}

istream& operator>> (istream &in, Rational &r){ // complete the code}

main(){ Rational rObj; cout << "Enter a rational number like 2/9: "; cin >> rObj; cout << "The rational number is: " << rObj << endl;};