oop objects_classes

31
Objects and Classes

Upload: sidra-tauseef

Post on 18-Nov-2014

153 views

Category:

Education


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Oop objects_classes

Objects and Classes

Page 2: Oop objects_classes

Objectives

To understand objects and classes, and the use of classes to model objects

To learn how to declare a class and how to create an object of a class

To understand the role of constructors when creating objects

To learn constructor overloading

To understand the scope of data fields (access modifiers), encapsulation

To reference hidden data field using the this pointer

Page 3: Oop objects_classes

Object-oriented Programming (OOP)

Object-oriented programming approach organizes programs in a way that mirrors the real world, in which all objects are associated with both attributes and behaviors

Object-oriented programming involves thinking in terms of objects

An OOP program can be viewed as a collection of cooperating objects

Page 4: Oop objects_classes

OO Programming Concepts

Classes and objects are the two main aspects of object oriented programming.

A class is an abstraction or a template that creates a new type whereas objects are instances of the class.

An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.

Page 5: Oop objects_classes

Classes in OOP

Classes are constructs/templates that define objects of the same type.

A class uses variables to define data fields and functions to define behaviors.

Additionally, a class provides a special type of function, known as constructors, which are invoked to construct objects from the class.

Page 6: Oop objects_classes

Objects in OOP

An object has a unique identity, state, and behaviors.

The state of an object consists of a set of data fields (also known as properties) with their current values.

The behavior of an object is defined by a set of functions

Page 7: Oop objects_classes

Class and Object

A class is template that defines what an object’s data and function will be. A C++ class uses variables to define data fields, and functions to define behavior.

An object is an instance of a class (the terms object and instance are often interchangeable).

Page 8: Oop objects_classes

UML Diagram for Class and Object

Circle radius: double Circle()

Circle(newRadius: double)

getArea(): double

circle1: Circle radius: 10

Class name

Data fields

Constructors and Methods

circle2: Circle radius: 25

circle3: Circle radius: 125

Page 9: Oop objects_classes

Class in C++ - Example

Page 10: Oop objects_classes

Class in C++ - Example class Circle { public: // The radius of this circle double radius; // Construct a circle object Circle() { radius = 1; } // Construct a circle object Circle(double newRadius) { radius = newRadius; } // Return the area of this circle double getArea() { return radius * radius * 3.14159; } };

Data field

Function

Constructors

Page 11: Oop objects_classes

Class is a Type

You can use primitive data types to define variables.

You can also use class names to declare object names. In this sense, a class is an abstract type, data type or user-defined data type.

Page 12: Oop objects_classes

Class Data Members and Member Functions

The data items within a class are called data members or data fields or instance variables

Member functions are functions that are included within a class. Also known as instance functions.

Page 13: Oop objects_classes

Object Creation - Instantiation

In C++, you can assign a name when creating an object.

A constructor is invoked when an object is created.

The syntax to create an object using the no-arg constructor is

ClassName objectName;

Defining objects in this way means creating them. This is also called instantiating them.

Page 14: Oop objects_classes

A Simple Program – Object Creationclass Circle{

private: double radius;

public:Circle(){ radius = 5.0; }double getArea(){ return radius * radius * 3.14159; }

};

Object InstanceC1

: C1 radius: 5.0

void main(){ Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea();}

Allocate memory for radius

Page 15: Oop objects_classes

Constructors

In object-oriented programming, a constructor in a class is a special function used to create an object. Constructor has exactly the same name as the defining class

Constructors can be overloaded (i.e., multiple constructors with different signatures), making it easy to construct objects with different initial data values.

A class may be declared without constructors. In this case, a no-argument constructor with an empty body is implicitly declared in the class known as default constructor

Note: Default constructor is provided automatically only if no constructors are explicitly declared in the class.

Page 16: Oop objects_classes

Constructors’ Properties

Constructors must have the same name as the class itself.

Constructors do not have a return type—not even void.

Constructors play the role of initializing objects.

Page 17: Oop objects_classes

Object Member Access Operator

After object creation, its data and functions can be accessed (invoked) using the (.) operator, also known as the object member access operator.

objectName.dataField references a data field in the object

objectName.function() invokes a function on the object

Page 18: Oop objects_classes

A Simple Program – Accessing Membersclass Circle{

private: double radius;

public:Circle(){ radius = 5.0; }double getArea(){ return radius * radius * 3.14159; }

};

Object InstanceC1

: C1 radius: 5.0

void main(){ Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea();}

Allocate memory for radius

Page 19: Oop objects_classes

Access Modifiers

Access modifiers are used to set access levels for classes, variables, methods and constructors

private, public, and protected

In C++, default accessibility is private

Page 20: Oop objects_classes

Data Hiding - Data Field Encapsulation

A key feature of OOP is data hiding, which means that data is concealed within a class so that it cannot be accessed mistakenly by functions outside the class.

To prevent direct modification of class attributes (outside the class), the primary mechanism for hiding data is to put it in a class and make it private using private keyword. This is known as data field encapsulation.

Page 21: Oop objects_classes

Hidden from Whom?

Data hiding means hiding data from parts of the program that don’t need to access it. More specifically, one class’s data is hidden from other classes.

Data hiding is designed to protect well-intentioned programmers from mistakes.

Page 22: Oop objects_classes

A Simple Program – Accessing Member Functionclass Circle{

private: double radius;

public:Circle(){ radius = 5.0; }double getArea(){ return radius * radius * 3.14159; }

};

Object InstanceC1

: C1 radius: 5.0

void main(){ Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea();}

Allocate memory for radius

Page 23: Oop objects_classes

A Simple Program – Default Constructorclass Circle{

private: double radius;

public:

double getArea(){ return radius * radius * 3.14159; }

};

// No Constructor Here

Object InstanceC1

void main(){ Circle C1; //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea();}

//Default ConstructorCircle() { }

: C1 radius: Any Value

Allocate memory

for radius

Page 24: Oop objects_classes

Object Construction with Arguments

The syntax to declare an object using a constructor with arguments is

ClassName objectName(arguments);

For example, the following declaration creates an object named circle1 by invoking the Circle class’s constructor with a specified radius 5.5.

Circle circle1(5.5);

Page 25: Oop objects_classes

A Simple Program – Constructor with Argumentsclass Circle{

private: double radius;

public:Circle(double rad){ radius = rad; }double getArea(){ return radius * radius * 3.14159; }

};

Object InstanceC1

: C1 radius: 9.0

void main(){ Circle C1(9.0); //C1.radius = 10; can’t access private member outside the class cout<<“Area of circle = “<<C1.getArea();}

Allocate memory for radius

Page 26: Oop objects_classes

Output of the following Program?class Circle{

private: double radius;

public:Circle(double rad){ radius = rad; }double getArea(){ return radius * radius * 3.14159; }

};

void main(){ Circle C1; cout<<“Area of circle = “<<C1.getArea();}

Page 27: Oop objects_classes

Constructor Overloadingclass Circle{

private: double radius;

public:Circle ()

{ radius = 1; } Circle(double rad)

{ radius = rad; }double getArea(){ return radius * radius * 3.14159; }

};

void main(){ Circle C2(8.0);

Circle C1; cout<<“Area of circle = “<<C1.getArea();}

Page 28: Oop objects_classes

The this Pointerclass Circle{

private: double radius;

public:Circle(double radius){ this->radius = radius; }double getArea(){ return radius * radius * 3.14159; }

};

void main(){ Circle C1(99.0); cout<<“Area of circle = “<<C1.getArea();}

Page 29: Oop objects_classes

The this Pointer

this is keyword, which is a special built-in pointer that references to the calling object.

The this pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions.

Can be used to access instance variables within constructors and member functions

Page 30: Oop objects_classes

ExerciseDesign a class named Account that contains: A private int data field named id for the account (default 0) A private double data field balance for the account (default 0) A private double data field named annualInterestRate that stores

the current interest rate (default 0). A no-arg constructor that creates a default account. A constructor that creates an account with the specified id, initial

balance, and annual interest rate. A function named getAnnualInterestRate() that returns the annual

interest rate. A function named withdraw that withdraws a specified amount

from the account. A function named deposit that deposits a specified amount to the

account. A function named show to print all attribute values Implement the class. Write a test program that creates an Account

object with an account ID of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the Annual interest, and the date when this account was created.

Page 31: Oop objects_classes

(Algebra: quadratic equations) Design a class named QuadraticEquation for a quadratic equation. The class contains:

Private data fields a, b, and c that represents three coefficients. A constructor for the arguments of a, b, and c. A function named getDiscriminant() that returns the discriminant, which

is b2 – 4ac The functions named getRoot1() and getRoot2() for returning two roots

of the equation

Implement the class. Write a test program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display the two roots. If the discriminant is 0, display the one root. Otherwise, display “The equation has no roots”.

Exercise