0% found this document useful (0 votes)
22 views37 pages

W4 Oop

Uploaded by

hoannguyendoduc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views37 pages

W4 Oop

Uploaded by

hoannguyendoduc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Protection Levels and Constructors

Introduction to Object-
Oriented Programming
Structural programming and object-oriented
programming

Structural (procedural) programming

Programming using well defined control structures
– Conditionals, loops, sequences, expressions and assignments
– Data (variables, arrays, structures) are separated from their operations
– It provides an abstraction of the hardware.

Object-oriented programming

Built on top of structural (procedural) programming

Programming based on the concept of object.
‒ Objects bundle data with their operations.
‒ Enables information hiding, which allow us to organize the program in a
more manageable way.
Object-Oriented basics

A fundamental concept in an object-oriented language is the
encapsulation of data and procedures (functions) together into
units called objects.

An object consists of:
– Name – a way of referring to an object inside a program (eg. A Fraction
object might be called F1).
– Member Data – data contained within an object (eg. Fraction has an integer
numerator and denominator).
– Member Functions – routines that act upon the data within an object (eg.
The fraction object might have a function that returns the decimal
representation of the fraction stored).
– Interface – defines the ways a programmer may directly access the member
data/functions of an object (more on this next lecture).
Classes

A class is another fundamental concept in an object-oriented
language that provides a blueprint for a new type
('classification') of object.

A class outlines the data, functions and the interface objects of that class
will receive.

A class also defines how objects of that class behave by providing code
that implements the functions associated with the class.

A programmer can create one or more objects from a class

Similar to building multiple houses from one set of blueprints.
How to define and use a class in a program

DDU – Declare, Define, Use

Declare a class
– Choose what objects of this class will store (member variables), and how
objects will behave (member functions).

Define member functions
– Provide an implementation for the member functions in the class.

Use class to create objects
– You can declare an new object instance of your class just like declaring any
other variable (eg. int x).
Example Class Declaration

class Circle
{
public: /* interface, we will cover later */
void SetRadius(double r); /* sets member variable radius to r */
double AreaOf(); /* returns area of circle as a double */
double radius; /* radius of circle stored as double */
}; /* don't forget ';' */
Define Member Functions

There are two ways to provide the member function definitions
for a class:

Inside the class declaration using {} (we will not use)

After the class declaration (this is the method we choose)

Refer to a member function:
className::memberFuntionName

This identifier refers to the member function memberFunctionName of
class className (e.g. Circle::SetRadius)

The double colon :: is called the scope resolution operator

After the class declaration, member functions are defined just
like any other function
Example member function definition
//Declaration:
class Circle
{
public:
void SetRadius(double r); /*sets member variable radius to r */
double AreaOf(); /* returns area of circle as a double */
private:
double radius; /* radius of circle */
};
/* Definition (Implementation) */
void Circle::SetRadius(double r)
{
radius = r; /* radius refers to this object’s member variable */
}
double Circle::AreaOf()
{
return (3.14*radius*radius);
}
Object Use

After a class has been declared and defined, an object of that class
can be declared (also known as creation or instantiation) and used, a
class is just like another type (int, char, etc).

A programmer can declare an object with the following format:
ClassName ObjectName;

This statement creates an object based on the blueprint of class
‘ClassName’ and the object can be referred to by the identifier
(variable name) ‘ObjectName’

The ‘ . ’ (dot) operator can be used to access an object’s public
members

The format for referring to an object’s member is:
ObjectName.MemberFunction() OR
ObjectName.MemberVariable
Putting it All Together

See sample1.cpp

To recap, this program:

declares the class Circle and outlines its members and interface

defines the implementation for the member functions of the Circle class

declares two objects of the class Circle, referred to as C1 and C2

uses the interfaces of C1 and C2 to store the radius of two circles and
later to calculate the area of those circles
Summary

An object is a unit that encapsulates data and functions. It has
four elements: a name, data members, function members, and
an interface.

A class specifies the (user-defined) form of objects.

The use of an object in a C++ program follows the declare,
define, and use sequence.

What does scope resolution operator (::) do?

What does the dot operator (.) do?
Review

What is an object?

What is a class?

What are the steps to creating a new object type and using it?

What is the scope resolution operator?
Protection Levels and Constructors
Class interface: Protection Levels and
Constructors
Protection Levels

When we design a class we can control how member functions


and data of that class can be accessed.
Each member of the class is assigned a protection level:
– Public Members : Object data and functions that can be accessed from
both outside and inside the member functions of the object.
– Private Members : Object data and functions that can be accessed only
from within member functions of the object.

Code that implements the class has accesses to private data, code that
uses the class does not have access to private data.
The primary purpose of protection levels is to allow programmers
to provide an unchanging public interface for a class while
being able to modify the way the class is implemented without
breaking code that uses the class.
This is a mechanism for information hiding.
sample1.cpp

Program output:
Decimal:0.5

Now lets uncomment line 33,


Compiler output:
sample1.cpp: In function ‘int main()’:
sample1.cpp:9: error: ‘int
Fraction::numer’ is private
sample1.cpp:33: error: within this
context
sample2.cpp

Program output:
Hello!!!
Decimal:0.5
With line 39 uncommented,
Compiler output:
sample2.cpp:32: error: ‘void
Fraction::PrintHello()’ is private
sample2.cpp:39: error: within this
context
More on Protection Levels

Reasons for data hiding (private members):


– Makes interface simpler for user.
– Principle of least privileged (need-to-know)
– More secure. Less chance for misuse (accidental or malicious).
– Class implementation easy to change without affecting other modules that
use it.

Other things to note:


– If protection levels not given, members default to private.
– When designing a class we should make private any members not part of
the class interface.
Constructors

A constructor is a special member function in a class whose


purpose is usually to initialize the members of an object.
A constructor is easy to recognize because:
It has the same name as the class.
It has no return type.
Circle Example:
Constructors continued

A constructor is a function so you can write any code inside it you


want.
What is special about constructors?
– Called automatically whenever you instantiate an object (eg. Circle C1; )
– The constructor function is not called explicitly (eg. C1.Circle())

The term default constructor refers to a constructor with no


parameters.
Every class must have a constructor, if you do not supply one an
empty default constructor is created automatically.
How do we pass arguments to constructors with parameters?
Passing Arguments to a Constructor

It is simple, really. Just add (…) as part of the object instantiation:


Circle C1(5); /* declares a new Circle object with the argument 5 passed to the
second Circle constructor as parameter r */
Let's look at the Fraction example...
Review

What are the protection levels in a class we talked about last time?

Why do we use protection levels?

Which part of program can access private data members? Which part
of program cannot access private data? What happens when the
program accesses private data illegally?

Which part of program can access private functions? Which part of
program cannot access private functions? What happens when the
program accesses private functions illegally?

What is a constructor?

How can you tell if a function is a constructor in a class?

What is a default constructor?

How to pass arguments to a constructor?
Review with
another view!!!
Class Methods
Class Methods
Constructors
Access
Specifiers
Inheritance
Protection Levels and Constructors
More about classes: friend, conversion
constructor, destructor
A Motivating Example

Suppose we want to write a function equals that compares 2


fraction objects and use it as follows

A possible definition for the function might be:


A Motivating Example (continue)

What if we want to write the equals function as follows:

Such functions are not member functions: can’t directly access the
private functions.
Such functions (e.g. comparing two objects) needs to access
private members frequently: we would like C++ to allow such
access.
C++ solution: the ‘friend’ keyword.
The ‘friend’ keyword

The friend keyword allows a class to grant full access to an outside entity

By "full access", we mean access to all the class' members, including the private
section.

An outside entity can be a function, or even another class (we'll focus on functions for
now).

To grant friend status, declaration of the "friend" is made inside the class
definition block, with the keyword friend in front of it.

A friend is neither public nor private, because by definition it is not a member of the
class. Just a friend. So it does not matter where in the block it is placed.

A friend function to a class will have full access to the private members of the class.
So, for example, the second definition of Equals() would be legal.

Look at the friend_fraction example.

This example contains the Equals() function given above.

This example also defines an Add() function, as a friend, for adding two Fractions
together and returning a result.

Includes a sample driver program that makes test calls to Equals() and Add().
Member function instead of a friend function

When a function works on two objects, it's often convenient to
pass both as parameters and make it a friend

Another option is to use a member function -- but one of the objects
must be the calling object

Example: The Equals() function could have been set up as a member
function, which would mean this kind of call:


In the above example, f1 is the calling object (ie. The object calling a
member function) and f2 is passed into f1's Equals function as an
argument.

Look at member_fraction example.
Member vs. Friend functions


Whether to make a function a friend or member of a class is usually a
stylistic decision.

Different programmers may have different preferences. Here's a
comparison of the calls, side-by-side:


One thing to notice are that the member and friend versions above
are not always equivalent

In the friend version of equals received copies of f1 and f2 (function cannot
change original fractions).

What about the member version?
Conversion Constructors

Some built-in types can perform automatic type conversion as
such:


We can also add this functionality to classes with a conversion
constructor.
Conversion constructors continue

A conversion constructor is a constructor with one parameter

Since a constructor creates/initializes a new object, we can use a
conversion constructor to convert a variable of that parameter's type to a
new object.

An example of a conversion constructor:


The above constructor could be used to perform automatic type
conversions as such:
Conversion constructors continue

A constructor with multiple parameters may be a conversion
constructor if all but one parameter is optional:
Fraction(int n, int d = 1);


Automatic type conversion for constructors can be suppressed
by using the keyword explicit in front of the declaration:
explicit Fraction(int n);


The above constructor will not auto-convert integers to
Fractions.

See convert_fraction example.
Destructors

In addition to the special constructor function, classes also have a special
function called a destructor.

The destructor looks like the default constructor (constructor with no
parameters), but with a ~ in front.

Destructors cannot have parameters, so there can only be one destructor for
a class.
Example: The destructor for the Fraction class would be: ~Fraction();


Like the constructor, this function is called automatically (not explicitly)

A destructor is called automatically right before an object is deallocated by
the system, usually when it goes out of scope (is no longer accessible by the
programmer).

The destructor's typical job is to do any clean-up tasks (usually involving
memory allocation) that are needed, before an object is deallocated.

See destructor.cpp example.

You might also like