0% found this document useful (0 votes)
130 views

W04-Classes and Objects: Constructor

This document discusses classes and objects in C++. It covers constructors, destructors, overloaded constructors, member functions, const and static members, passing and returning objects from functions. It provides examples of a Date class and Time class to demonstrate these concepts, including defining the classes, implementing member functions, and using objects of the classes.

Uploaded by

ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views

W04-Classes and Objects: Constructor

This document discusses classes and objects in C++. It covers constructors, destructors, overloaded constructors, member functions, const and static members, passing and returning objects from functions. It provides examples of a Date class and Time class to demonstrate these concepts, including defining the classes, implementing member functions, and using objects of the classes.

Uploaded by

ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Spring 2016

W04-Classes and Objects


Abstraction and Encapsulation

Constructor and Destructor


Overloaded Constructors
Member Function Overloading
Const & Static Members
Passing & Returning Objects from Functions

Constructor

 A constructor is a special function that is


automatically invoked when a new object of a
class is instantiated.

 The constructor must always have the same


name as the class and has no return type.

 Constructors can be overloaded.

W03- Classes and Objects


27

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 1
Destructor
 Just like a Constructor, Destructor is also a special function.
which is automatically invoked when an object is destroyed.

 The most common use for destructor is to deallocate


dynamically allocated memory.

 Example:
class Date
{
public:
Date(); // constructor
~Date(); // destructor

};

W03- Classes and Objects


28

Example: The Date Class


class Date
{
private:
int day, month, year; // data members

public:
Date() // default constructor
{ day = 1; month = 1; year = 2000;}
Date (int d, int m, int y); // parameterized constructor
void setYear(int y);
void setMonth(int m);
void setDay(int d);
void show(); // displays date
};
W03- Classes and Objects
29

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 2
Class Implementation
Date::Date (int d, int m, int y)
{
day=d;
month=m;
year = y;
}

void Date::setMonth (int m)


{
month=m;
}

W03- Classes and Objects


30

Class Implementation
void Date::setDay (int d)
{
day = d; }

void Date::setYear (int y)


{
year=y; }

void Date::show()
{
cout <<day << ”-” <<month << ”-” <<year<< endl;
}

W03- Classes and Objects


31

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 3
Instantiation of Objects
void main ()
{
Date d1 (14,8,1947);
Date d2 (22,2,2016);
Date d3;
d1.show(); d2.show(); d3.show();
d3.setYear(2016);
d3.show();
}

W03- Classes and Objects


32

Copy Constructor
 The copy constructor initializes an object with
another object of the same class.

 Each class possesses a built-in default copy constructor.

 Example:
void main()
{
Date d1(12,4,1997);
Date d2(d1); // default copy constructor
Date d3=d1; // default copy constructor
}

W03- Classes and Objects


33

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 4
Time Class Definition
class Time {
public:
Time(); // Overloaded Constructors
Time(int, int, int);
// set functions
void setHour(int); // set hour
void setMinute(int); // set minute
void setSecond(int); // set second
// get functions
int getHour(); // return hour
int getMinute(); // return minute
int getSecond(); // return second
void printUniversal(); // print universal time format
void printStandard(); // print standard time format
private:
int hour; // 0 - 23
int minute; // 0 - 59
int second; // 0 - 59
};
W03- Classes and Objects
34

Time Class Implementation


// Default constructor initializes each data member to zero.
Time::Time()
{ hour = minute = second = 0; }

// Set a new Time value using universal time. Perform validity


// checks on the data values. Set invalid values to zero.
Time::Time(int h, int m, int s)
{
setHour(h);
setMinute(m);
setSecond(s);
}

W03- Classes and Objects


35

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 5
Time Class Implementation
// Set values using universal time. Perform validity
// checks on the data values. Set invalid values to zero.
void Time :: setHour (int h)
{
hour = (h >= 0 && h < 24) ? h : 0; }

void Time :: setMinute (int m)


{
minute = (m >= 0 && m < 60) ? m : 0; }

void Time :: setSecond (int s)


{ second = (s >= 0 && s < 60) ? s : 0; }

W03- Classes and Objects


36

Time Class Implementation


// Print Time in universal format
void Time::printUniversal()
{
cout << (hour < 10 ? "0" : "") << hour << ":"
<< (minute < 10 ? "0" : "") << minute << ":"
<< (second < 10 ? "0" : "") << second; }

// Print time in standard format


void Time::printStandard()
{
cout << ((hour == 0 || hour == 12) ? 12 : hour % 12)
<< ":" << (minute < 10 ? "0" : "") << minute
<< ":" << (second < 10 ? "0" : "") << second
<< (hour < 12 ? " AM" : " PM");
}
W03- Classes and Objects
37

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 6
Driver to Test Class Time
int main()
{
Time t; // instantiate object t of class Time
cout << "The initial universal time is ";
t.printUniversal();
cout << endl << "The initial standard time is ";
t.printStandard();

Time t1(4,23,45);
cout << endl << “Universal time is ";
t.printUniversal();
cout << endl << "Standard time is ";
t.printStandard();
return 0;
}

W03- Classes and Objects


38

UML Diagram for Rectangle class

Rectangle
length
width

setLength()
setWidth()
getLength()
getWidth()
getArea()

W03- Classes and Objects


39

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 7
UML Data Type and Parameter Notation

 UML diagrams use language independent


notations to show return types, access modifiers,
etc.

Rectangle

Access modifiers
are denoted as: - width : double
+ public
- private
+ setWidth(w : double) : void

W03- Classes and Objects


40

UML Data Type and Parameter Notation

 UML diagrams use language independent


notations to show return types, access modifiers,
etc.

Variable types are


Rectangle placed after the
variable name,
separated by a colon.
- width : double

+ setWidth(w : double) : void

W03- Classes and Objects


41

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 8
UML Data Type and Parameter Notation

 UML diagrams use language independent


notations to show return types, access modifiers,
etc.

Function return types are


Rectangle placed after the function
declaration name,
separated by a colon.
- width : double

+ setWidth(w : double) : void

W03- Classes and Objects


42

UML Data Type and Parameter Notation

 UML diagrams use language independent


notations to show return types, access modifiers,
etc.

Function parameters
Rectangle
are shown inside the
parentheses using the
same notation as
- width : double
variables.

+ setWidth(w : double) : void

W03- Classes and Objects


43

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 9
Converting the UML Diagram to Code
class Rectangle
{ private:
double width;
double length;
Rectangle public:
void setWidth(double w)
- width : double {
- length : double }
void setLength(double len)
+ setWidth(w : double) : void {
+ setLength(len : double): void }
double getWidth()
+ getWidth() : double
{ return 0.0;
+ getLength() : double }
+ getArea() : double double getLength()
{ return 0.0;
}
double getArea()
{ return 0.0;
W03- Classes and Objects }
44
};

Class Member Function Overloading


class Point {
public:
void init(int u, int v) {
x = u; y = v;
}
void print();
void print(char *s);

private:
int x,y;
};
W03- Classes and Objects
45

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 10
Class Member Function Overloading

void Point::print() {
cout << “(” << x << “,” << y << “)”;
}

void Point::print(char *s) {


cout << s;
print();
}

W03- Classes and Objects


46

Const Objects
 const specify that an object is not modifiable

 Any attempt to modify the object is a syntax


error

 Example
const Time noon( 12, 0, 0 );

W03- Classes and Objects


47

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 11
Const Member Functions
 A member function that is declared as const does not
modify the data of the object
class Date
{
int year() const; // const doesn’t modify data
void addYear(int n); // non-const modifies data
};

int Date::year() const // defined as const


{ return year; }

int Date::addYear(int n)
{ year+=n; }
W03- Classes and Objects
48

Static Member Data


 Normally each object possesses its own separate copy of
data members, called Instance data

 A static data member is shared among all objects of the


same class

 There is exactly one copy of a static data member


rather than one copy per object as for non-static
(instance) variables

W03- Classes and Objects


49

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 12
Instance vs. Static Data Members

W03- Classes and Objects


50

Example: Using a Static Data Member


class P {
public:
static char c;
};

char P::c = ‘W’;

int main () {
P x,y;
cout << x.c;
x.c = ‘A’;
cout << y.c;
}
W03- Classes and Objects
51

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 13
Static Member Data
class Foo
{
public:
Foo() { counter++; }
~Foo() { counter--; }
void display()
{
cout << ”There are ” << counter << ” Foo objects!”;
}
private:
static int counter;
};

W03- Classes and Objects


52

Static Member Data


int Foo::counter = 0;

int main()
{ Foo f1;
Foo f2;
f1.display();
{ Foo f3;
f2.display(); }
f1.display();
return 0; }
W03- Classes and Objects
53

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 14
Objects as Function Arguments
Class Distance
{
private:
int feet;
float inches
public:
Distance() : feet(0),inches(0.0)
{ }

Distance(int ft, float in):feet(ft),inches(in)


{ }

W03- Classes and Objects


54
54

Objects as Function Arguments


void getDist ( )
{
cout << “Enter feet : “ ; cin >> feet;
cout << “\nEnter inches : “ ; cin >> inches;
}

void showDist ( )
{ cout <<feet << “ \’ ” << inches <<“ \” “; }

void addDist(Distance, Distance);


};

W03- Classes and Objects


55
55

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 15
Objects as Function Arguments
void Distance :: addDist(Distance d1, Distance d2)
{ inches = d1.inches + d2.inches;
feet = 0;
if (inches >= 12.0)
{ inches -= 12.0;
feet++;
}
feet += d1.feet + d2.feet;
}

W03- Classes and Objects


56
56

Objects as Function Arguments


int main()
{
Distance dist1, dist3;
Distance dist2(10, 3.5);
dist1.getDist();
dist3.addDist(dist1, dist2);
cout << “\ndist1 = “ ; dist1.showDist();
cout << “\ndist2 = “ ; dist2.showDist();
cout << “\ndist3 = “ ; dist3.showDist();
return 0;
}

W03- Classes and Objects


57
57

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 16
Returning Objects from Functions
Distance Distance :: addDist(Distance d)
{
Distance temp;
temp.inches = inches + d.inches;
if (temp.inches >= 12.0)
{ temp.inches -= 12.0;
temp.feet =1;
}
temp.feet += feet + d.feet;
return temp;
}

W03- Classes and Objects


58
58

Returning Objects from Functions

int main()
{
Distance dist1,dist2;
Distance dist3(11,6.5);
dist1.getdist();
dist2 = dist1.addDist(dist3);

cout << “\ndist1 = “ ; dist1.showDist();


cout << “\ndist2 = “ ; dist2.showDist();
cout << “\ndist3 = “ ; dist3.showDist();
return 0;
}

W03- Classes and Objects


59
59

Object Oriented Programming - Spring 2016


Instructor: Saima Jawad 17

You might also like