You are on page 1of 19

About Instructor

Mr. Fayez Afzaal


Lecturer
Department of Computer Science
COMSATS University Islamabad,
Sahiwal Campus, Pakistan
Email: Fayez@cuisahiwal.edu.pk
Object-Oriented Programming
in C++

Lecture 2
Constructors
 A type of member function that is automatically executed when an object of that class is created is
known as constructor.
 The constructor has no return type and has same name that of class name
 The constructor can work as a normal function but it cannot return any value.
 It is normally defined in classes to initialize data member
 Automatic initialization is carried out using a special member function called a constructor without
requiring a separate call to a member function
 Syntax
name() {
constructor body
}
 name it indicates the name of the constructor. The name must be same as the name of
the class in which the constructor is declared
 Write a class that displays a simple message on the screen whenever an object of that class is created
class Hello{
private:
int n; Output
public: Object created…
Hello(){ Object created…
cout<<“object created…”<<endl; }}; Object created…
void main()
{ Hello x, y, z;
Program Example

#include <iostream> int main() Output


using namespace std; { c1=0
class Counter Counter c1, c2; //define and initialize c2=0
{ cout << “\nc1=” << c1.get_count(); //display c1=1
private: cout << “\nc2=” << c2.get_count(); c2=2
unsigned int count; //count c1.inc_count(); //increment c1
public: c2.inc_count(); //increment c2
Counter() : count(0) //constructor c2.inc_count(); //increment c2
{ /*empty body*/ } cout << “\nc1=” << c1.get_count(); //display again
void inc_count() //increment count cout << “\nc2=” << c2.get_count();
{ count++; } cout << endl;
int get_count() //return count return 0;
{ return count; } }
};

 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).
someClass() : m1(7), m2(33), m2(4) ← initializer list
{ }
Passing Parameters to
Constructor
 The method of passing parameters to a constructor is same as passing parameters to normal
functions
 The only difference is that parameters are passed to the constructor when the object is declared
 The parameters are written in parenthesis along with the object name in declaration statement
 Syntax
 type object_name(parameters);
 type It is the name of a class and indicates the type of the object to be created
 object_name It indicates the name of the object to be created
 parameters It indicates the list of parameters passed to the constructor
Constructor Overloading
 The process of declaring multiple constructors with same name but different parameters is known as
constructor overloading.
 The constructors with same name must differ in one of the following ways:
 Number of parameters
 Type of parameters
 Sequence of parameters

 Program Example

 Write a class that has num and ch as data members. A constructor with no parameters initializes num
to 0 and ch to ‘x’. A constructor with two parameters initializes data members with the given values
and member function show displays the values of data members
Constructor Overloading
Example
class Over{ int main() Output
private: { Over first, second(100,'p'); The contents of first:
int num; cout<<"The contents of first:"<<endl; num=0
char ch; first.show(); ch=x
public: cout<<"The contents of second:"<<endl; The contents of second:
Over(){ second.show(); num= 100
num=0; } ch=p
ch='x';
}
Over(int n, char c){
num=n;
ch=c;
}
void show(){
cout<<"num ="<<num<<endl;
cout<<"ch ="<<ch<<endl;
}
};
Destructors
 A type of member function that is automatically executed when an object of that class is destroyed
is known as destructor
 The destructor has no return type and its name is same as class name
 The destructor cannot return any value. It also cannot accept any parameters
 The destructor name is preceded by tilde sign ~.
 The most common use of destructors is to deallocate memory that was allocated for the object by
the constructor.
 Syntax
 The syntax of declaring destructor is as follows:
~name(){
destructor body
}
 ~name It indicates the name of the destructor. The name must be same as the name of the class
in which the constructor is declared
Destructor Program
Example
#include<iostream>
using namespace std;
class Test
{ Output
private: Object created…
int n; Object created…
public: Object destroyed…
Test(){ Object destroyed…
cout<<"Object created ..."<<endl;
}
~Test(){
cout<<"Object destroyed ..."<<endl;
}
};
int main()
{
Test a,b;
}
Default Copy Constructor
 We’ve seen two ways to initialize objects. A no-argument constructor can initialize data members
to constant values, and a multi-argument constructor can initialize data members to values
passed as arguments.
 Let’s mention another way to initialize an object: you can initialize it with another object of the same type
 A type of constructor that is used to initialize an object with another object of the same type is known as
default copy constructor
 The user does not need to write this constructor.
 It accepts a single object of the same type as parameters
 The parameter for default copy constructor can be given in parenthesis or using assignment operator

 Syntax
 class_name object_name(parameter); OR
 class_name object_name=parameter;
 class_name It is the name of a class and indicates the type of object to be created
 object_name It indicates the name of the object to be created
 parameter It indicates the name of parameter that is passed to default copy constructor
The values of data members of parameter object are copied to data members of the
new object. The type of new object and parameter object must be same
Program Example
//initialize objects using default copy constructor
#include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
//constructor (no args)
Distance() : feet(0), inches(0.0)
{}
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{}
void getdist() //get length from user
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
Program Example…
void showdist() //display distance
{ cout << feet << “\’-” << inches << ‘\”’;
} Output
}; dist1 = 11’-6.25”
//////////////////////////////////////////////////////////////// dist2 = 11’-6.25”
int main() dist3 = 11’-6.25”
{
Distance dist1(11, 6.25); //two-arg constructor

Distance dist2(dist1); //one-arg constructor

Distance dist3 = dist1; //also one-arg constructor

//display all lengths


cout << “\ndist1 = “; dist1.showdist();
cout << “\ndist2 = “; dist2.showdist();
cout << “\ndist3 = “; dist3.showdist();
cout << endl;
return 0;
}
Objects as Function Arguments
 It also demonstrates some new aspects of classes: constructor overloading, defining member functions
outside the class, and perhaps most importantly objects as function arguments.

 Example
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{}
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{}
void getdist() //get length from user
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches; }
Objects as Function Arguments
void showdist() //display distance int main()
{ cout << feet << “\’-” << inches << ‘\”’; } {
void add_dist( Distance, Distance ); //declaration Distance dist1, dist3; //define two lengths
}; Distance dist2(11, 6.25); //define and initialize dist2
//-------------------------------------------------------------- dist1.getdist(); //get dist1 from user
//add lengths d2 and d3 dist3.add_dist(dist1, dist2); //dist3 = dist1 + dist2
void Distance::add_dist(Distance d2, Distance d3) //display all lengths
cout << “\ndist1 = “; dist1.showdist();
{ cout << “\ndist2 = “; dist2.showdist();
inches = d2.inches + d3.inches; //add the inches cout << “\ndist3 = “; dist3.showdist();
feet = 0; //(for possible carry) cout << endl;
if(inches >= 12.0) //if total exceeds 12.0, return 0;
{ //then decrease inches }
inches -= 12.0; //by 12.0 and
feet++; //increase feet
} //by 1
feet += d2.feet + d3.feet; //add the feet
}
Output
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.75
dist1 = 17’-5.75”
dist2 = 11’-6.25”
dist3 = 29’-0”
Defining Member
Functions outside Class

 The member function of a class can also be defined outside the class.
 The declaration of member functions is specified within the class and function definition is specified
outside the class.
 The scope resolution operator :: is used in function declaratory if the function is defined outside the
class.
 Syntax
 return_type class_name :: function_name(parameters) {
function body
}
 return_type it indicates the type of value to be returned by the function
 class_name it indicates the name of the class to which the function belongs
 :: it is the scope resolution operator to define member function outside class
 function_name it is the name of the member function to be defined
 function_body it is the body of the function
Returning Objects from Functions
 We saw objects being passed as arguments to functions. Now we’ll see an example of a function that
returns an object.
 If a member function returns an object, its return type should be the same as the type of the object to
be returned
//function returns value of type Distance
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{}
void getdist() //get length from user
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
Returning Objects from
Functions
void showdist() //display distance int main()
{ cout << feet << "\'-" << inches << '\"'; } {
Distance dist1, dist3; //define two lengths
Distance add_dist(Distance); //add Distance dist2(11, 6.25); //define, initialize dist2
}; dist1.getdist(); //get dist1 from user
//-------------------------------------------------------------- dist3 = dist1.add_dist(dist2); //dist3 = dist1 + dist2
//add this distance to d2, return the sum //display all lengths
Distance Distance::add_dist(Distance d2) cout << "\ndist1 = "; dist1.showdist();
{ cout << "\ndist2 = "; dist2.showdist();
Distance temp; //temporary variable cout << "\ndist3 = "; dist3.showdist();
temp.inches = inches + d2.inches; //add the inches cout << endl;
if(temp.inches >= 12.0) //if total exceeds 12.0, return 0;
{ //then decrease inches }
temp.inches -= 12.0; //by 12.0 and
temp.feet = 1; //increase feet
} //by 1
temp.feet += feet + d2.feet; //add the feet
return temp;
}
Output
Enter Feet: 10
Enter inches: 5.6

dist1 = 10’ – 5.6”


dist2 = 11’ – 6.25”
dist3 = 21’ – 11.85”

 One distance, dist2, is passed to add_dist() as an argument. It is added to the object, dist1, of which
add_dist() is a member, and the result is returned from the function. In main(), the result is assigned to dist3
in the statement dist3 = dist1.add_dist(dist2);

You might also like