Lectures notes on OOP, Lecture notes of Object Oriented Programming

Lectures notes on OOP in Computer Science

Typology: Lecture notes

2024/2025

Uploaded on 03/21/2026

bongoni-ojok-okwir
bongoni-ojok-okwir 🇰🇪

1 document

1 / 28

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Object Oriented Programming (OOP) Lecture Rasha thamer shawi
Computer Science Department- Education College 2nd stage - Morning study
1
Lecture 4
CONSTRUCTORS AND DESTRUCTORS
4.1 Introduction
C++ provides a special member function called the constructor
which enables an object to initialize itself when it is created. This is known
as automatic initialization of objects. It also provides another member
function called the destructor that destroys the objects when they are no
longer required.
4.2 constructors
A constructor is a „special‟ member function whose task is to initialize
the objects of its class. A constructor is a member function that is
executed automatically whenever an object is created. It is special
because its name is the same as the class name. The constructor is invoked
whenever an object of its associated class is created. It is called constructor
because it construct the values of data members of the class.
A constructor is declared and defined as follows:
// class with a constructor
class integer
{
int m , n;
public:
integer ( void ); // constructor declared
…….
……
};
integer:: integer (void ) // constructor defined
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download Lectures notes on OOP and more Lecture notes Object Oriented Programming in PDF only on Docsity!

Computer Science Department- Education College 2nd stage - Morning study

Lecture 4

CONSTRUCTORS AND DESTRUCTORS

4.1 Introduction

C++ provides a special member function called the constructor which enables an object to initialize itself when it is created. This is known as automatic initialization of objects. It also provides another member function called the destructor that destroys the objects when they are no longer required.

4.2 constructors

A constructor is a „special‟ member function whose task is to initialize the objects of its class. A constructor is a member function that is executed automatically whenever an object is created. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it construct the values of data members of the class. A constructor is declared and defined as follows: // class with a constructor class integer { int m , n; public: integer ( void ); // constructor declared ……. …… }; integer :: integer (void ) // constructor defined

Computer Science Department- Education College 2nd stage - Morning study

{ m=0; n=0; } When a class contains a constructor like the one defined above, it is guaranteed that an object created by the class will be initialized automatically. For example, the declaration

integer int1 ; //object int1 created

Not only creates the object int1 of type integer but also initializes its data member's m and n to zero. A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A( ). If no such constructor is defined, then the compiler supplies a default constructor. Therefore a statement such as ( A a ; ) Invokes the default constructor of the compiler to create the object a. The constructor functions have some special characteristics:  They should be declared in the public section.  They are invoked automatically when the objects are created.  They do not have return types, not even void and therefore, they cannot return values.  They cannot be inherited, though a derived class can call the base class constructor.  Like other C++ functions, they can have default arguments.  We can be defined as inline function

Computer Science Department- Education College 2nd stage - Morning study

This statement creates an integer object int1 and passes the values 0 and 150 to it. The second is implemented as follows: integer int1(0,150) ; //implicit call ( shorthand )

// Class with Constructors // #include using namespace std; class integer { int m , n; public: integer ( int , int ); //constructor declared void display (void); }; integer :: integer (int x , int y ) // constructor defined { m = x; n = y; } void integer :: display (void) { cout << ” m = “ << m << “\n”; cout << ” n = “ << n << “\n”; } main () { integer int1(0,100); //implicit call integer int2= integer(25,75); //explicit call cout << “\n OBJECT1” << “\n”;

Computer Science Department- Education College 2nd stage - Morning study

int1.display( ); cout << “\n OBJECT2” << “\n”; int2.display( ); } The output of above program is: OBJECT m = 0 n= 100 OBJECT m = 25 n= 75

Example:-This example, COUNTER, provides a counter variable that can be modified only through its member functions. // counter.cpp // object represents a counter variable #include using namespace std; class Counter { private: int count; //count public: Counter (): count (0) //constructor { /empty body/ } void inc_count() //increment count { count++; } int get_count() //return count { return count; } };

Computer Science Department- Education College 2nd stage - Morning study

count() : count(0) { } The initialization takes place following the member function declaratory but before the function body. It‟s preceded by a colon. The value is placed in parentheses following the member data. If multiple members must be initialized, they‟re separated by commas. The result is the initializer list (sometimes called by other names, such as the member-initialization list). some Class() : m1(7), m2(33), m2(4) ← initializer list { } Why not initialize members in the body of the constructor? The reasons are complex, but have to do with the fact that members initialized in the initializer list are given a value before the constructor even starts to execute. This is important in some situations. For example, the initializer list is the only way to initialize const member data and references. Actions more complicated than simple initialization must be carried out in the constructor body, as with ordinary functions. They‟re separated by commas. The result is the initialize list: Some Class (): m1(7), m2(33), m3(4) ← initialize list { }

Counter Output The main() part of this program exercises the Counter class by creating two counters, c1 and c2. It causes the counters to display their initial values, which—as arranged by the constructor—are 0. It then increments c1 once and c2 twice, and again causes the counters to display themselves (non-criminal behavior in this context). Here‟s the output: c1= c2=

Computer Science Department- Education College 2nd stage - Morning study

c1= c2= Example:- #include using namespace std; class operations { float a,b,c; int ch; public: operations( ); void result( ); }; operations::operations( ) { cout<<"Mathematical Operations \n"; cout<<" 1- Addition \n"; cout<<" 2- Subtraction \n"; cout<<" 3- Multiplication \n"; cout<<" 4- Division \n"; cout<<" Please Enter your choice : \n"; cin>>ch; cout<<" Please Enter two Values a and b \n"; cin>>a>>b; } void operations::result( ) { switch (ch) { case 1: c=a+b; cout< Computer Science Department- Education College 2nd stage - Morning study

// implementation of destructors // #include using namespace std; int count=0; class alpha { public: alpha() { count++; cout<< “\nNO.of object created “ << count; } ~alpha() { cout<< “\nNO.of object destroyed “ << count ; count--; } }; main() { cout<< “\n\nEnter Main\n; alpha A1,A2,A3,A4; { cout << “\n\nEnter Block1\n”; alpha A5; } { cout << “\n\nEnter Block2\n”; alpha A6;

Computer Science Department- Education College 2nd stage - Morning study

} cout<< “\n\nRE-Enter Main\n; }

#include #include using namespace std; int count=0; class alpha { public: alpha() { count++; cout<< "\nNO.of object created " << count ; } ~alpha() {

Computer Science Department- Education College 2nd stage - Morning study

Note: - As the objects are created and destroyed, they increase and

decrease the count. Notice that after the first group of objects is

created, A5 is created, and then destroyed, A6 is created, and then

destroyed. Finally, the rest of the objects are also destroyed. When

the closing brace of a scope is encountered, the destructors for

each object in the scope are called. Note that the objects are

destroyed in the reverse order of creation.

4.5 Multiple Constructors in A Class

So far we have used two kinds of constructors. They are: integer(); //No arguments integer(int , int); //two arguments In the first case, the constructor itself supplies the data values and no values are passed by the calling program. In second case, the function call passes the appropriate value from main (). C++ permits us to use both these constructors in the same class. For example, we could define a class as follows: class integer { int m,n; public: integer() { m=0; n=0; } //constructor 1 integer(int a , int b ) {m = a ; n = b;} //constructor 2 integer(integer &i) {m = i. m ; n = i. n;} //constructor 3 };

Computer Science Department- Education College 2nd stage - Morning study

This declares three constructors for an integer object. The first constructor receives no arguments, the second, receivers' two integer arguments, and the third receives one integer object as an argument. For example, the declaration: integer l1 ; Would automatically invoke the first constructor and the set both m and n of l1 to zero. The statement integer l2 (20 , 40) ; Would call the second constructor, which will initialize the data members m and n of l2 to 20 and 40 respectively. Finally, the statement integer l3 (l2) ; Would invoke the third construct which copies the value of l2 into l3. That is, it sets the value of every data element of l3 to the value of corresponding data element of l2. Such a constructor is called the copy constructor****. When more than one constructor function is defined in a class, we say that the constructor is overloaded.

// Overloading Constructor // Example:- Create a class that imitates part of the functionality of the basic data type int. Call the class Int (note different capitalization). The only data in this class is an int variable. Include member functions to initialize an Int to 0, to initialize it to an int value, to display it (it looks just like an int), and to add two Int values. Write a program that exercises this class by creating one uninitialized and two initialized Int values, adding the two initialized values and placing the response in the uninitialized value, and then displaying this result.(Instead of having z=x+y, and x,y and z are int , we could have z.add(x,y) and x,y and z are of type Int.)

Computer Science Department- Education College 2nd stage - Morning study

4.6 Objects as Function Arguments

Our next program adds some new aspects of classes: constructor overloading, defining member functions outside the class, and perhaps most importantly objects as function arguments. Here‟s the listing for ENGLCON: // englcon.cpp // constructors, adds objects using member function #include using namespace std; class Distance //English Distance class { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } Distance(int ft, float in) : feet(ft), inches(in) //constructor (two args) { } void getdist() //get length from user { cout << "\nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; } void showdist() //display distance { cout << feet << "'-" << inches << '"';} void Distance::add_dist(Distance d2, Distance d3) { inches = d2.inches + d3.inches; //add the inches feet = 0; //(for possible carry)

Computer Science Department- Education College 2nd stage - Morning study

if(inches >= 12.0) //if total exceeds 12.0, { //then decrease inches inches -= 12.0; //by 12.0 and feet++; //increase feet } //by 1 feet += d2.feet + d3.feet; } //add the feet }; main() { Distance dist1, dist3; //define two lengths Distance dist2(11, 6.25); //define and initialize dist dist1.getdist(); //get dist1 from user dist3.add_dist(dist1, dist2); //dist3 = dist1 + dist2 //display all lengths cout << "\ndist1 = "; dist1.showdist(); cout << "\ndist2 = "; dist2.showdist(); cout << "\ndist3 = "; dist3.showdist(); cout << endl; }

This program starts with a distance dist2 set to an initial value and adds to it a distance dist1, whose value is supplied by the user, to obtain the sum of the distances. It then displays all three distances: Enter feet: 17 Enter inches: 5. dist1 = 17’-5.75” dist2 = 11’-6.25” dist3 = 29’-0” It‟s convenient to be able to give variables of type Distance a value when they are first created. That is, we would like to use definitions like: Distance width (5, 6.25);

Computer Science Department- Education College 2nd stage - Morning study

Member Functions Defined Outside the Class In ENGLCON the add_dist() function is defined following the class definition. //add lengths d2 and d void Distance::add_dist(Distance d2, Distance d3) { inches = d2.inches + d3.inches; //add the inches feet = 0; //(for possible carry) if(inches >= 12.0) //if total exceeds 12.0, { //then decrease inches inches -= 12.0; //by 12.0 and feet++; //increase feet } //by 1 feet += d2.feet + d3.feet; //add the feet } The declarator in this definition contains some unfamiliar syntax. The function name, add_dist(), is preceded by the class name, Distance, and a new symbol—the double colon (::). This symbol is called the scope resolution operator. It is a way of specifying what something is associated with.

Computer Science Department- Education College 2nd stage - Morning study

Ex:- constructor function #include using namespace std; class myclass { int a; public: my class( ); // constructor function void show( ); }; myclass::myclass( ) { cout<<"constructor function \n"; a=10; } void myclass::show( ) { cout<