You are on page 1of 16

Data Structures using OOP C++

Lecture 1

References: 1. E Balagurusamy ,Object Oriented Programming with C++, 4th edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

Introduction
There are two weaknesses related with structured programming. Firstly, functions have unrestricted access to global data. This causes a programs structure difficult to conceptualize. In addition, it makes the program difficult to modify. Any change made in a global data item may necessitate rewriting all the functions that access that item. Secondly, the arrangement of separate data and functions does a poor job of modeling things in the real world. In the real world we deal with objects such as people and cars. Such objects arent like data and they arent like functions. Complex real-world objects have both data and functions. Therefore there was a need for a new programming approach which is called Object-Oriented Programming.

Object-Oriented Programming (OOP)


OOP incorporates the best features of structured programming with several powerful new concepts. It provides a new way of thinking, organizing and developing programs. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. The data of
Ass. Lec. Zainab Mahmood Fadhil Page 1

Data Structures using OOP C++

Lecture 1

an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects.

Fundamental OOP Concepts


The principles of OOP include: Class: is like a blueprint (general form) used to create objects. A class also is an abstract data type that can be treated like any other built-in data type. A class defines the attributes of its objects and the methods that can be applied to its objects. Object: is the basic run-time entity in an object-oriented system. It may represent a person, a place, a bank account, etc. An object is also called an instance of a class. Encapsulation: is the mechanism that binds together data and functions into a single unit (called class). The data is not accessible to the outside world, and only the functions which are wrapped in the class can access it. This insulation of data from direct access is called data hiding or information hiding. Inheritance: is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. It also provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. Polymorphism: is the ability for objects of different classes related by inheritance to respond differently to the same message. The same message sent to many different types of objects takes on many forms--hence the term polymorphism.
Ass. Lec. Zainab Mahmood Fadhil Page 2

Data Structures using OOP C++

Lecture 1

Classes
The general form of a class declaration in C++ is:
class class_name { private: variable function public: variable function };

declarations; declarations; declarations; declarations;

- The keyword class indicates that an abstract data type called class_name will be specified. - The class body is enclosed within braces and terminated by a semicolon. - The variables declared inside the class are known as data members and the functions are known as member functions. - These functions and variables are usually grouped under two sections: namely, private and public. - Only the member functions can have access to the private data members and private functions. However, the public members can be accessed from outside the class. - Note that declaring data variables as public defeat the idea of data hiding and therefore should be avoided.

Ass. Lec. Zainab Mahmood Fadhil

Page 3

Data Structures using OOP C++

Lecture 1

A Simple Class Example


class item { private: int number; float cost; public: void getdata(int void putdata(); };

a, float

b);

Here, we have defined a class called item. This name is used to declare objects of that class. The data members (number and cost) are declared as private, while the member functions (getdata() and putdata()) are declared as public. As mentioned earlier, these two functions provide the only access to the two data members from outside the class. Note that, at this stage class definition does not allocate any memory space.

Objects
Once a class has been defined, we can create objects of that type as follows:
item x;

This statement creates an object x of type item. At this stage, memory space is allocated to the object x. We may also declare more than one object in one statement, for example
item x, y, z;

Another way to create objects is by placing their names immediately after the closing brace in the class definition, for example:

Ass. Lec. Zainab Mahmood Fadhil

Page 4

Data Structures using OOP C++

Lecture 1

class {

item

} x, y, z;

Accessing Class Members


As previously mentioned, the public member functions can be accessed only from outside the class. This can be done using the dot operator, for example
x.getdata(100, 75.5);

This function call statement is valid and assigns the value 100 to number and 75.5 to cost of the object x by implementing the getdata() function. Similarly, the statement
x.putdata();

would display the values of number and cost. While the statement
x.number =100;

is illegal because number is a private member and cannot be accessed from outside the class. When a variable is declared as public, it can be accessed by the objects directly, for example:

Ass. Lec. Zainab Mahmood Fadhil

Page 5

Data Structures using OOP C++

Lecture 1

class xyz { private: int int public: int }; xyz p; p.x = 0; p.z = 10;

x; y; z;

// create object p // error, x is private // OK, z is public

However, the public declaration of data conflicts with the OOP concept data hiding and therefore should be avoided.

Definition of Member Functions


Class member functions can be defined in two places: Outside the Class Definition Example:
void { item :: getdata(int a, float b) number = a; cost = b; }

Here, the membership label item :: tells the compiler that the function
getdata() belongs to the class item. That is, the scope of the function getdata() is restricted to the class item specified in the header line.

The symbol :: is called the scope resolution operator. Note the statements
number = a; cost = b;

Ass. Lec. Zainab Mahmood Fadhil

Page 6

Data Structures using OOP C++

Lecture 1

show that the member functions can have direct access to private data items. Similarly, the function putdata() is defined outside the class
item as follows: void { item :: putdata() cout << Number : << number << \n ; cout << Cost : << cost << \n ; }

Inside the Class Definition Example:


class item { private: int number; float cost; public: void getdata(int a, float b); void putdata() { cout << Number : << number << \n ; cout << Cost : << cost << \n ; } };

Note: Normally, only small functions are defined inside the class definition.

A Complete C++ Program with Class


The following program includes all the details discussed so far:
#include <iostream> using namespace std; class item { private: int number; float cost;
Ass. Lec. Zainab Mahmood Fadhil Page 7

Data Structures using OOP C++

Lecture 1

public: void getdata(int a, float b); void putdata() { cout << number : << number << \n; cout << cost : << cost << \n; } }; void { item :: getdata(int a, float number = a; cost = b; } void { main() item x; //create object cout << \nObject x << \n; x.getdata(100, 299.95); x.putdata(); x b)

item y; //create another object y cout << \nObject y << \n; x.getdata(200, 175. 50); x.putdata(); }

The output of the above program is: Object x number :100 cost :299.95 Object y number :200 cost :175.5

Ass. Lec. Zainab Mahmood Fadhil

Page 8

Data Structures using OOP C++

Lecture 1

Nesting of Member Functions


We have shown that a class member function can be called only by an object of that class using a dot operator. However, a member function can be called inside another member function of the same class. This is called nesting of member functions. Example:
#include <iostream> using namespace std; class set { private: int m, n; public: void input(); void display(); int largest(); }; int { set :: largest() if(m >= n) return m; else return n; } void set :: input() { cout << Input values of m and n << \n; cin >> m >> n; } void set :: display() { cout << Largest value = << largest() << \n; } void main() {
Ass. Lec. Zainab Mahmood Fadhil Page 9

//calling member function

Data Structures using OOP C++

Lecture 1

set A; A.input(); A.display(); }

The output of the above program would be: Input values of m and n 25 18 Largest value = 25

Private Member Functions


Some tasks such as deleting a customer account, or providing an increment to an employee may require certain functions to be hidden (like private data) from the outside calls. We can place these functions in the private section. Note that a private member function can only be called by another member function of its class, and cannot be called by an object. Example:
class sample { private: int void public: void void }; sample s1; s1.read();

m; read(); update(); write();

// private member function

// wont work; objects cannot access // private members from outside the class

The function call statement


s1.read();
Ass. Lec. Zainab Mahmood Fadhil Page 10

Data Structures using OOP C++

Lecture 1

is illegal. Instead, the function read() can be called by the function


update() to update the value of m. void { read(); } // simple call; no object used sample :: update()

Constructors
A constructor is a member function whose name is the same as the class name. The constructor is used to initialize the objects of its class, i.e. it constructs the values of data members of the class. The constructor is automatically invoked whenever object of its associated class is created. Example:
#include <iostream> using namespace std; class integer { private: int m, n; public: integer(); // constructor declaration void printdata(); }; integer :: integer() // constructor definition { m = 0; n = 0; } void integer :: printdata() { cout << m = << m << \n << n = << n << \n; } void main() {

Ass. Lec. Zainab Mahmood Fadhil

Page 11

Data Structures using OOP C++

Lecture 1

integer intl; intl.printdata(); }

The declaration statement


integer intl;

not only creates the object intl of type integer but also automatically initializes its data members m and n to zero. The output of the above program is m=0 n=0 Notes The constructor should be declared in the public section. The constructor does not have return type, (not even void), and therefore it cannot return any value. There is no need to write any statement to invoke the constructor function because it is invoked automatically when the object is created. A constructor that accepts no arguments is called the default constructor. If no constructor is defined, then the compiler creates an implicit constructor. The constructor can take arguments like other C++ functions. This is called parameterized constructor.

Parameterized Constructors
Sometimes we need to initialize the data elements of different objects with different values when they are created. This can be done by passing
Ass. Lec. Zainab Mahmood Fadhil Page 12

Data Structures using OOP C++

Lecture 1

arguments to the constructor function when objects are created. Such constructor is called parameterized constructor. Example:
#include <iostream> using namespace std; class integer { private: int m, n; public: integer(int , int ); //parameterized constructor void printdata(); }; integer :: integer(int x, int y) { m = x; n = y; } void integer :: printdata() { cout << m = << m << \n <<n = << n << \n; } void main() { integer intl(1, 100); intl.printdata(); }

The output of the above program is m=1 n = 100 Note that when we use parameterized constructor, we must pass the initial values as arguments to the constructor function when an object is declared. For example, in the above program, the following declaration statement
integer intl;

may not work. In this case we need to define multiple constructors as in the following example:
Ass. Lec. Zainab Mahmood Fadhil Page 13

Data Structures using OOP C++

Lecture 1

#include <iostream> using namespace std; class integer { private: int m, n; public: integer(); integer(int , int ); //parameterized constructor void printdata(); }; integer :: integer() { m = 0; n = 0; } integer :: integer(int x, int y) { m = x; n = y; } void integer :: printdata() { cout << m = << m << \n <<n = << n << \n; } void main() { integer intl1, intl2(1, 100); cout<<OBJECT 1 \n; intl1.printdata(); cout<<OBJECT 2 \n; intl2.printdata(); }

The output of the above program is OBJECT 1 m=0 n=0 OBJECT 2 m=1 n = 100 Note: When more than one constructor function is defined in a class, we say that constructor overloading.

Ass. Lec. Zainab Mahmood Fadhil

Page 14

Data Structures using OOP C++

Lecture 1

Destructors
A destructor is a member function whose name is the same as the class name but is preceded by a tilde ~ . The destructor is used to destroy the objects that have been created by a constructor. For example, the destructor for the class integer is defined as follows:
~integer() { }

Notes A destructor never takes any arguments nor does it return any value. A destructor will be invoked implicitly by the compiler upon exit from the program (or block or function) to free memory space. Example:
#include <iostream> using namespace std; int count = 0; class alpha { public : alpha () { count++; cout << \nObject# << count << is created ; } ~alpha() { cout << \nObject# << count << is destroyed ; count--; } }; void main() { cout << \n\nENTER MAIN\n; alpha A1, A2, A3, A4;
Ass. Lec. Zainab Mahmood Fadhil Page 15

Data Structures using OOP C++

Lecture 1

{ cout << \n\nENTER BLOCK\n; alpha A5; alpha A6; } cout << \n\nRE-ENTER MAIN THEN EXIT PROGRAM; }

The output of the above program is: ENTER MAIN Object#1 is created Object#2 is created Object#3 is created Object#4 is created ENTER BLOCK Object#5 is created Object#6 is created Object#6 is destroyed Object#5 is destroyed

RE-ENTER MAIN THEN EXIT PROGRAM Object#4 is destroyed Object#3 is destroyed Object#2 is destroyed Object#1 is destroyed

Note that the objects are destroyed in the reverse order of creation.

Ass. Lec. Zainab Mahmood Fadhil

Page 16

You might also like