W4 Oop
W4 Oop
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
Program output:
Decimal:0.5
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
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.