Class, Constructors And Destructors
F2010/9/1
UNIT9
Class, Constructors And Destructors
OBJECTIVES
General Objective :
To understand and apply the fundamental concept of class structure in C++ programming
Specific Objective :
At the end of the unit you should be able to :-
State the basics of a program Recognize the class structure Differentiate between Constructors and Destructors. Write and design a simple program
________________________________________________________________________
Class, Constructors And Destructors
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.
Class is combination of data declarations and function declarations
________________________________________________________________________
Class, Constructors And Destructors
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:
________________________________________________________________________
Class, Constructors And Destructors
F2010/9/4
class Cat { unsigned int unsigned int Meow(); }; itsAge; itsWeight;
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
Figure 9.3: An Object Of A Class Definition
________________________________________________________________________
Class, Constructors And Destructors
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; }
Figure 9.4: An Example Of Inline Specifier
________________________________________________________________________
Class, Constructors And Destructors
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.
________________________________________________________________________
Class, Constructors And Destructors
F2010/9/7
Cbase
CDerived1 inherits from its parent class;CBASE CDerived1
CDerived2
CDerived2 inherits from its parent class:Cderived1 and inherits CBase in the process
Figure 9.5: A Class Hierarchy
9.6 Specifying Access Control
Access Specifier
Meaning
public
Class members are accessible by any object
Private
Class members are accessible only by the class itself
Protected
Class members are accessible by the class itself and any classes derived from the classes.
Figure 9.6: An Example of Specifying Access Control
________________________________________________________________________
Class, Constructors And Destructors
F2010/9/8
9.7
Specifying Access Program
// 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
Figure 9.7: An Example of Specifying Public Access
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.
________________________________________________________________________
Class, Constructors And Destructors
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
________________________________________________________________________
Class, Constructors And Destructors
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.
________________________________________________________________________
Class, Constructors And Destructors
F2010/9/11
9.8.1 Default Constructor
It does not require any arguments.
// Class Declaration Class employee { private: int id; double salary; public: employee(); void assign_values(const int, const double); void display_values(); }; // constructor for employee object employee::employee() { cout << \n Enter constructor; id = 0; salary = 0.0 cout << |n Exit constructor; } void employee:: assign_values(const int id2,const double salary2) { id= id2; salary = salary2; } void employee:: display_values() { cout<<\nEmployee id: <<id; cout<<\nEmployee salary: <<salary; cout << endl; } void main() { employee emp; // constructor is called emp.display_values(); values of variables after the call emp.assign_values(111,500.00); // the values are changed emp.display_values(); cout<<endl; }
Figure 9.9: An Example Of Default Constructor
________________________________________________________________________
Class, Constructors And Destructors
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.
9.8.2 Copy constructor
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.
________________________________________________________________________
Class, Constructors And Destructors
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
________________________________________________________________________
Class, Constructors And Destructors
F2010/9/14
9.9.1 The Destructor Function
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.
Do not hesitate to see your lecturer if you do not understand
________________________________________________________________________
Class, Constructors And Destructors
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.2 The inline function is used for _____________________.
9.3 Data Encapsulation is ________________________
9.4 Explain the difference between a constructor and destructor.
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? };
________________________________________________________________________
Class, Constructors And Destructors
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.
________________________________________________________________________
Class, Constructors And Destructors
F2010/9/17
Key Facts
Class is combination of data declarations and function declarations.
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
________________________________________________________________________
Class, Constructors And Destructors
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
a. What is the difference between a declaration and a definition?
b. When will the copy constructor be called?
c. When will the destructor be called?
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.
________________________________________________________________________
Class, Constructors And Destructors
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.
________________________________________________________________________
Class, Constructors And Destructors
F2010/9/20
e. class SimpleCircle { public: SimpleCircle(); ~SimpleCircle(); void SetRadius(int); int GetRadius(); private: int itsRadius; }; f. SimpleCircle::SimpleCircle(): itsRadius(5) {}
CONGRATULATIONS May success be with you.
________________________________________________________________________