Unit 9 - Object Oriented Programming / C++
Unit 9 - Object Oriented Programming / C++
F2010/9/1
UNIT9
OBJECTIVES
General Objective :
To understand and apply the fundamental concept of class structure in C++ programming
Specific Objective :
State the basics of a program Recognize the class structure Differentiate between Constructors and Destructors. Write and design a simple program
________________________________________________________________________
F2010/9/2
INPUT
9.0
Introduction To Class
A class is a programmer defined data typed. It is able to hold data and methods (functions) that operate on data. Classes form the basis for object-oriented programming (OOP). A class is a collection of variables often of different types combined with a set of related functions. A class is a template where users are able to create objects, which are simply instances of that class. A class encapsulates (contain) both data structures, methods (functions) and these are available to every object belonging to that class to be executed repeatedly until a certain condition is reached. Data or Variable is referred to as class attributes while the term methods is used to refer to the class function. Methods that contained within the class (or member methods) can access its data. Data and methods contained in a class are called their member data and member methods.
________________________________________________________________________
F2010/9/3
9.1
Class Declaration
A class declaration is a new type that links code and data. This new data is then used to declare objects of the class. A class declaration is similar syntactically to structure. A class declaration takes the general form of:
Class class_name { private: // can be dropped variable declarations; function declarations; public: variable declarations; function declarations; }
Figure 9 .1: An Example of A Class Declaration To declare a class, use the class keyword followed by an opening brace and then list the data members and methods of that class. End the declaration with a closing brace and a semicolon. Here is the declaration of a class called Cat:
________________________________________________________________________
F2010/9/4
Figure 9.2: An Example Of A Class Definition Declaring this class does not allocate memory for a Cat. It tells the compiler what a Cat is, what data it contains (itsAge and itsWeight) and what it can do (Meow( )). It also tells the compiler how big a Cat is that is, how much room the compiler must set aside for each Cat that you create. In this example, if an integer is two bytes, a Cat is only four bytes big: itsAge is two bytes, and itsWeight is another two bytes. Meow( ) takes up no room because no storage space is set aside for member functions (methods).
9.2 Defining an Object
You define an object of your new type just as you define an integer variable:
unsigned int GrossWeight; // define an unsigned Cat Frisky;
integer
// define a Cat
________________________________________________________________________
F2010/9/5
This code defines a variable called Gross Weight whose type is an unsigned integer. It also defines Frisky, which is an object whose class (or type) is Cat. All items defined in class are private. That means they cannot be accessed by any function which is not a member of the class.
9.3
InLine function
The inline function is used to eliminate the overhead that associated with the function call and return mechanism. Therefore it can be executed much faster that generate the function call and return takes time each time a function is called. Inline function is same as an ordinary function, except for the use of the inline specifier.
inline int cube(int n) { return n*n*n; }
________________________________________________________________________
F2010/9/6
9.4
Data Encapsulation
A class binds its data and functions together. That means its data (functions) can only be accessed by functions from within that class. A class binds them into a cohesive unit. Encapsulation makes complex process easier by hiding the complexity from the user.
Encapsulation is the bundling or packaging of data and functions into a single unit
9.5
Class Hierarchies
Class hierarchy is comprised of different levels of inheritance among a group of related classes that work together to provide solutions to programming pro blems. When designing a class hierarchy, a class base must be implemented. Based on figure as shown below, a base class CBase and its derived class Cderived1 . Now imagine that class Cderived2 inherited from CDerived1. These classes form a simple hierarchy that is often presented in a tree format.
________________________________________________________________________
F2010/9/7
Cbase
CDerived2
CDerived2 inherits from its parent class:Cderived1 and inherits CBase in the process
Access Specifier
Meaning
public
Private
Protected
Class members are accessible by the class itself and any classes derived from the classes.
________________________________________________________________________
F2010/9/8
9.7
// Class Declaration Class employee { private: int id; double salary; public: void assign_values(const int, const double); void display_values(); }; // class implementation void employee:: assign_valu es(const int id2,const salary2) { id= id2; salary = salary2; } void employee:: display_values() { cout<<\nEmployee id: <<id; cout<<\nEmployee salary: <<salary; } double
In figure 9.7, the data members id and salary are private to the class while the member functions assign_values and display_values are public. That means id and salary can only be accessed by assign_values and display_values. Functions external to the class ( e.g main( ) )or functions from another class cannot access these variables. The function assign_values and display_values on the other hand can be accessed by any function from within or outside the class. This is because their scope is public.
________________________________________________________________________
F2010/9/9
9.8
Constructors
A constructor is called when an object is being created. Constructors can be overloaded to allow different approaches of object construction. There are seve ral common types of constructor, including default constructors, copy constructor and default parameter constructors. The rules for constructors are as follows: 1. Constructor has the same name as the class name. 2. It does not return a value. 3. It cannot pass arguments to a constructor.
A constructor is a special type of member function that is automatically called each time when an object is created
________________________________________________________________________
F2010/9/10
#include <iostream> class myclass{ int a; public: myclass (); // constructor void show (); }; myclass:myclass() { cout << In constructor \n ; a = 10; } void myclass::show() { cout << a; } int main() { myclass ob; ob.show(); return 0; }
Figure 9.8: An Example Of Constructor In this example, the value of a is initialized by the constructor myclass(). The constructor is called when the object ob is created. An object is created when that objects declaration statement is executed.
________________________________________________________________________
F2010/9/11
F2010/9/12
In this program, the data members in an employee object will be set by default. That means any subsequent instantiation of the class results in an object with the zero value the variables id and salary. These values can be changed with the assign_value function.
Is a constructor function designed to copy objects of the same class type. It accepts a single argument (a reference to the same class type) and returns a copy of an object. The copy constructor is called whenever c ode is passed on an object to a function by value instead of reference. The copy constructor is also called if initializing a new object with another object of the same type for example:
CPoint3d pt1 (1.0f,2.0f,3.0f); // default constructor CPoint3d pt2 new CPoint3d(pt1) // copy constructor
The copy constructor initializes the values from existing object to a new object of having the same class type. To create a copy constructor for CPoint3d class, the function in the class should be first declared.
CPoint3d(const CPoint3d& pt)
Here the CPoint3d constructor takes a constant reference to an existing CPoint3d object. The goal of the copy constructor is to make a copy of pt.
________________________________________________________________________
F2010/9/13
The const keyword is used to ensure that the copy constructor does not alter the data of the object being passed into the function. Next, define the actual copy constructor in the class definition:
CPoint3d :: CPoint3d(conts CPoint3d& pt) { this-> x = pt.x; this-> y = pt.y; this-> z = pt.z; }
9.9
Destructors
A destructor is a function (method) that is called automatically when an object is destroyed. The destructor reclaims the memory allocated to the object. It performs close-up operations
The rule for destructors are as follows: a. A destructor has the same name as the class name but it has a tilde(~) in front of it. b. A destructor does not return a value. c. Cannot pass any arguments to a destructor. d. Cannot have more than one destructor for a class
________________________________________________________________________
F2010/9/14
The destructor receives no parameters so it can be overloaded. A classs destructor name is comprised of a tilde (~) followed by the name of the class as in ~CPOint3d(). The destructor for the CPoint3d class looks like this:
CPoint3d ::~CPoint3d() { }
There is no code in the destructor function body because the CPoint3d class does not require any cleanup.
________________________________________________________________________
F2010/9/15
Activity 9
Test your comprehension before continuing the next input. Check your answers on the next page. 9.1 What is a class?
9.5 Identify the error of declaration shown below? class Square { public: int Side; }
9.6 Identify the error of the constructor shown in the following fragment? Class sample { double a,b,c; Public: double sample();// error ,why? };
________________________________________________________________________
F2010/9/16
Feedback 9
Make sure you have tried to answer all the questions given. You can check your answers with the answers below. 9.1 Collection of variables are often of different types combined with a set of related functions. 9.2 To eliminate the overhead that is associated with the function call and return mechanism. 9.3 A class binds its data and functions together. That means, their data(functions) can only be accessed by functions from within that class. 9.4 Constructors are called when an object is being created. Constructors can be overloaded to allow different approaches of object construction Destructor is a function (method) that is called automatically when an object is destroyed. The destructor reclaims the memory allocated to the object. It performs close-up operations.
9.5 No semicolon after close braces. 9.6 A constructor cannot have a return value.
________________________________________________________________________
F2010/9/17
Key Facts
To declare a class, use the class keyword followed by an opening brace and then lists the data members and methods of that class. End the declaration with a closing brace and a semicolon.
Encapsulation is the bundling or packaging of data and functions into a single unit.
Class hierarchy is comprised of different levels of inheritance among a group of related classes that work together to provide solutions to programming problems .
A constructor is a special type of member function that is automatically called each time when an object is crea ted.
A destructor is a function (method) that is called automatically when an object is destroyed. The destructor reclaims the memory allocated to the object. It performs close-up operations
________________________________________________________________________
F2010/9/18
Self-Assessment
You are approaching success, please answer the questions below. If you have any problems, please discuss it with your lecturer. Wish you good luck and all the best.
Question 9 - 1
d. How does the copy constructor differ from the assignment operator (=)?
e. Write a SimpleCircle class declaration (only) with one member variable: itsRadius. Include a default constructor, a destructor, and accessor methods for itsRadius.
f. Using the class you created in Question e, write the implementation of the default constructor, initializing itsRadius with the value 5.
________________________________________________________________________
F2010/9/19
Feedback On Self-Assessment
Make sure you have tried to answer all the questions given. You can check your answers with the answers below.
Answer 9 - 1
a. A definition sets aside memory, but a declaration does not. Almost a ll declarations are definitions, but the major exceptions are class declarations, function prototypes, and typedef are statements.
b. Whenever a temporary copy of an object is created. This happens every time an object is passed by a value.
c. The destructor is called each time an object is destroyed, either because it goes out of scope or because you call delete on a pointer pointing to it.
d. The assignment operator acts on an exi sting object; the copy constructor creates a new one.
________________________________________________________________________
F2010/9/20
e. class SimpleCircle { public: SimpleCircle(); ~SimpleCircle(); void SetRadius(int); int GetRadius(); private: int itsRadius; }; f. SimpleCircle::SimpleCircle(): itsRadius(5) {}
________________________________________________________________________