Vous êtes sur la page 1sur 33

9 - User

User--defined Data Types

COL 100 - Introduction to Computer


p
Science
II Semester 2015-2016
Department of Computer Science and Engineering
Indian Institute of Technology Delhi

Aggregate Data
Arrays
All elements are of the same type

Structure/Record/Class
Combining elements of different types

April 2016

(C) P. R. Panda, IIT Delhi

Grouping related variables


Complex Numbers:
x + iy
real part
(x: float)
imaginary
i
i
partt
(y: float)

float ar,
ar br; /* real part */
float ai, bi; /* imaginary part */
float cr[10];
fl
[10] /* reall part */
float ci[10]; /* imaginary part */

Need to indicate
relationship between
x and y
Naming conventions
(ar, ai)

ar and
d aii are related,
l t d b
butt
this is not captured in declarations

not formal
April 2016

(C) P. R. Panda, IIT Delhi

Aggregate Data: struct or


records/structures
struct represents
aggregate
t data
d t
real and imag are
fields/members in
the struct
related data are
grouped into one
logical unit

April 2016

struct complex_num
complex num {
float real;
float imag;
g;
};

(C) P. R. Panda, IIT Delhi

Accessing struct fields


complex_num is
a User-defined
D t T
Data
Type
complex_num can
be used just like
any other type
a,, b are variables
of this new type
c is an array of
complex
l numbers
b

struct complex_num {
fl t real;
float
l
float imag;
} a, b;
complex_num c[10];
...
a.real = 1.0;;
b.real = 2.0;
c[0].real = a.real * b.real - a.imag*b.imag;
c[0].imag = a.real * b.imag + a.imag * b.real;

Member Access
Operator: .
April 2016

(C) P. R. Panda, IIT Delhi

Hierarchical Composition
Structs can be
hi
hierarchically
hi ll
composed of other
structs
t t
Structs and Arrays
arrays within structs
arrays of structs

April 2016

struct Date {
int day;
int month;
int year;
};
struct Employee {
char name [20];
int employee_num;
int ssalary;
y;
Date joining_date;
};
Employee
p y emp_list
p_
[[1000];
];
...
emp_list [5].salary = 0;
emp_list [5].joining_date.year = 2014;

(C) P. R. Panda, IIT Delhi

Space Occupied by a struct


Could be more than sum of parts
Some members ((e.g.,
g , int)) mayy be aligned
g
to word
(e.g., 32-bit) boundary
a
Use sizeof() to determine size
struct x {
int a; // 4 bytes
y
int b; // 4 bytes
char c; // 1 byte
char d; // 1 byte
};

a
b
c
d

struct x {
int a; // 4 bytes
char c;
int b; // 4 bytes
char d;
};

b
d

Ch k using
Check
i sizeof()!
i
f()!
April 2016

(C) P. R. Panda, IIT Delhi

Initialising and Copying a struct


Initialisation similar to array
initialisation
Assignment causes memberwise copy
all members are individually
copied
array members are also copied
note difference from array

struct x {
i ta
int
char b [5];
float c;
};
...
x t1 = {{3, xyz,
y 1.0};
}
x t2 = t1;

E
Equality
lit ttestt (==,
(
!=)
! ) nott
allowed
April 2016

(C) P. R. Panda, IIT Delhi

Passing structs as Function


Parameter
Pass by Value
means struct
t t is
i
copied
Potentially
expensive!
large array
members are
copied
i d

April 2016

struct Employee {
int salary;
char name [100];
};
void print (Employee e) {
cout << e.salary << , << e.name;
}
int main ()
{
Employee t1 = {1,
{1 Ajay Palvayanteeswaran};
};
print (t1);
}
(C) P. R. Panda, IIT Delhi

Pass structs by Reference


Passing by
R f
Reference
avoids
id
copying costs
use const if
parameter is
READ ONLY
READ-ONLY

April 2016

struct Employee {
int salary;
char name [100];
};
void
oid print (const Employee
Emplo ee &e) {
cout << e.salary << , << e.name;
}
int main ()
{
Employee t1 = {1, Ajay
Palvayanteeswaran};
print (t1);
}

(C) P. R. Panda, IIT Delhi

10

Same Issue with Returning struct


from Function
return causes
entire struct to
p
be copied
2 possibly
expensive copy
operations

April 2016

struct Employee {
intt sa
salary;
a y;
char name [100];
};
Employee update (Employee e) {
e.salary--;
return e;
}
int main ()
{
E l
Employee
t1
t1;...
t1 = update (t1);
}

(C) P. R. Panda, IIT Delhi

11

Return Data through Parameters


Passed by
y Reference
Passing
parameters by
Reference
avoids copying

April 2016

struct Employee {
intt sa
salary;
a y;
char name [100];
};
void update (Employee &e)
{
e.salary--;
}
int main ()
{
E l
Employee
t1
t1;...
update (t1);
}

(C) P. R. Panda, IIT Delhi

12

Implementing struct access


How do we implement
e.salary-- ?
e.name [[i]] = r ?

April 2016

struct
str
ct Employee
Emplo ee {
int id;
int salary;
char name [100];
};
void update (Employee &e)
{
e.salary--;
e.name
e
a e [[10]
0] = r;;
}
int main ()
{
Employee t1;...
update (t1);
}

(C) P. R. Panda, IIT Delhi

13

Implementing struct access


Need
N d St
Startt Address
Add
off e

Address_e

Fixed offset of salary


4 Bytes from start of struct
Address_e + 4

Fixed offset of name


8 Bytes from start of struct
then index expression
Address_e + 8 + i * (sizeof(char))

April 2016

struct
str
ct Employee
Emplo ee {
int id;
int salary;
char name [100];
};
void update (Employee &e)
{
e.salary--;
e.name
e
a e [[10]
0] = r;;
}
int main ()
{
Employee t1;...
update (t1);
}

(C) P. R. Panda, IIT Delhi

14

Representing an Enumeration
Employees Designation:

Intern
Engineer
Assistant Manager
Deputy Manager
Associate Manager
Manager
Senior Manager

Designation can take a small, fixed


number of values

struct Employee {
int salary;
??? title;
char name [100];
}
};
int main ()
{
Employee t1;
t1.title = ...;
}

integer is not the right abstraction


April 2016

(C) P. R. Panda, IIT Delhi

15

Problem
with int
int??
Lost connection
between Employee
and Designation!
nothing
thi iindicates
di t
that Employee and
the following const
ints are related

April 2016

struct
t t Employee
E l
{
int salary;
int title;
char name [100];
};
const int INTERN = 0;
const int ENGINEER = 1;
const int ASST_MANAGER = 2;
const int DEPUTY_MANAGER
DEPUTY MANAGER = 3;
const int ASSOCIATE_MANAGER = 4;
const int MANAGER = 5;
const int SENIOR_MANAGER
SENIOR MANAGER = 6;
int main ()
{
Emplo ee t1
Employee
t1;
t1.title = ASST_MANAGER;
}
(C) P. R. Panda, IIT Delhi

16

Representing Enumeration with


enum
Enumeration
contains list of
allowed values
More expressive
than than
t1.title = 2

enum Designation {INTERN, ENGINEER,


ASST_MANAGER,, DEPUTY_MANAGER};
};
struct Employee {
int salary;
Designation
g
title;
char name [100];
};
int main ()
{
Employee t1;
t1.title
1 i l = ASST
ASST_MANAGER;
MANAGER
}

April 2016

(C) P. R. Panda, IIT Delhi

17

Using enum in switch


Enum can be
used in switch
expression
Compiler can
warn if all cases
not covered
cant warn if int
type

April 2016

enum Designation {INTERN, ENGINEER,


ASST_MANAGER, DEPUTY_MANAGER};
struct Employee
p y {
int salary;
Designation title;
char name [100];
};
int main ()
{
Employee t1;
t1.title = ASST_MANAGER;
switch (t1.title) {
case INTERN:
INTERN ... break;
b k
case ASST_MANAGER: ...break;
}
}
(C) P. R. Panda, IIT Delhi

18

Data Type and Operations


complex_num and
abs are related
abs implements a
fundamental
property of
complex_num type

But, the struct and


function are not
specified as related
April 2016

struct complex_num {
float re;
float im;
} x;
float abs (const complex_num
complex num &a) {
return sqrt (a.re*a.re + a.im*a.im);
}
int main () {
float t1 = abs (x);
}

(C) P. R. Panda, IIT Delhi

19

Data Type and Operations


struct and function
are not specified
as related
y
Parameter type
doesnt tell enough
compare
p
function
add_top
abs seems more
fundamental
property of
complex num
complex_num
April 2016

struct complex_num {
float re;
float im;
} x, y[10];
int top = 0;
float abs (const complex_num
complex num &a) {
return sqrt (a.re*a.re + a.im*a.im);
}
void add_top
add top (const complex_num
complex num &a) {
y [top++] = a;
}
int main () {
float t1 = abs (x);
add_top (t1);
}

(C) P. R. Panda, IIT Delhi

20

Generalising structs
structs:: Classes
Class: General user-defined type
what data types?
what operations?

A data type and its relevant operations


grouped into a Class
Class consists of
of:
data types (member data, similar to struct)
associated operations (member
(
ffunctions))
access control (hide data from those who dont
need
d it)
April 2016

(C) P. R. Panda, IIT Delhi

21

Defining a Class
Complex Number data
type
same MEMBER DATA as in
struct
PRIVATE DATA real/imag
are not visible outside class
definition (default)
MEMBER FUNCTIONS for
modifying member data

Foundations of
Object-oriented
Programming
April 2016

class complex_num {
private:
float real;
float imag;
p blic
public:
void set_r (float r) {real = r;}
void set_i (float i) {imag = i;}
float get_r () {return real;}
float get_i () {return imag;}
...
};

(C) P. R. Panda, IIT Delhi

22

Accessing Classes
Access
ccess cclass
ass data
through member
functions
called methods

What is the advantage?


Public data members
could also be directly
accessed
discouraged
struct is just a special
class with members
public by default
April 2016

class complex_num {
private:
i t
float real;
float imag;
public:
void set_r (float r) {real = r;}
void set_i ((float i)) {{imag
g = i;}
;}
float get_r () {return real;}
float get_i () {return imag;}
} x;
main ()
{
x real = 9.0;
x.real
9 0; // NOT Allowed!
x.set_r (9.0);
// Modify ONLY through set_r ()
}

(C) P. R. Panda, IIT Delhi

23

Object: Instantiation of a Class


x and y are OBJECTS
generalisation
li ti off variable
i bl

Created when scope is


reached
x: global
y
y: when f is called

Destroyed when out of


scope
y: when we exit f

All member
data/functions
/f
visible to
member functions
e.g.,
e g real
April 2016

class complex_num {
private:
i t
float real;
float imag;
public:
void set_r (float r) {real = r;}
void set_i ((float i)) {{imag
g = i;}
;}
float get_r () {return real;}
float get_i () {return imag;}
} x; // Global object
void f ()
{
complex num y; // Local Object
complex_num
x.set_r (2.0)
y.set_r (9.0);
}

(C) P. R. Panda, IIT Delhi

24

Class Declaration and Definition


Class Declaration:
External Interface
goes into .h file (similar to
function declaration)
included elsewhere

Class Definition:
Internal Implementation
goes into .cpp file (similar
to function definition)
Scope Resolution
Operator :: needed to
specify scope explicitly
April 2016

class complex_num {
private:
float real;
float imag;
p blic
public:
void set_r (float r);
...
};
void complex_num::set_r (float r) {
real = r;
}

(C) P. R. Panda, IIT Delhi

25

Initialising an Object
Most common action
after declaring an
object is to initialise it
Member functions
could be used
left to programmer
common error:
forgetting
g
g to initialise a
variable

April 2016

(C) P. R. Panda, IIT Delhi

class complex_num {
private:
float real;
float imag;
public:
void
oid set_r
set r (float r)
r);
void set_i (float i);
...
};
int main () {
complex_num c;
c.set_r (0.0);
c.set_i (0.0);
}
26

An Initialiser Function
A member function init
could be invoked to
initialise data
Still, how do we insist
that user should call it?
class designer may
have default initial
values for member data

April 2016

(C) P. R. Panda, IIT Delhi

class complex_num {
private:
float real;
float imag;
public:
void set_r (float r);
void set_i (float i);
void
oid init (float rr, float i) {
real = r; imag = i;
}
...
};
int main () {
complex_num c;
c.init (0.0, 0.0);
}
27

Constructor for a Class


CONSTRUCTOR is a
special member function
meant for initialisation
name matches class name
no return type
called implicitly when object
is created
not called explicitly
otherwise, like a normal
function

April 2016

class complex_num {
private:
float real;
float imag;
g
public:
void set_r (float r);
void set_i
set i (float i);
complex_num (float r, float i) {
real = r; imag = i;
}
};
int main () {
comple n m c (1.0,
complex_num
(1 0 1.0);
1 0)
...
}

(C) P. R. Panda, IIT Delhi

28

Overloaded
Constructors
Can have multiple
constructors
with different signatures

Class designer can


provide default initial
values if user doesnt
doesn t
need not be fixed

April 2016

class complex_num {
private:
i t
float real;
float imag;
public:
void set_r (float r);
void set_i
_ ((float i);
)
complex_num (float r, float i) {
real = r; imag = i;
}
complex_num () {
real = 0.0; imag = 0.0;
}
};
int main () {
comple n m c (1.0,
complex_num
(1 0 1.0);
1 0)
complex_num d; // (0.0, 0.0)
}

(C) P. R. Panda, IIT Delhi

29

Default Constructor Parameters


Same effect as
for normal
functions
Abbreviation for
overloaded
constructors

April 2016

class complex
p _num {
private:
float real;
float imag;
public:
void set_r (float r);
void set_i
set i (float i);
complex_num (float r=0.0, float i=0.0) {
real = r; imag = i;
}
};
int main () {
complex_num c (1.0, 1.0);
complex_num d; // (0.0, 0.0)
}
(C) P. R. Panda, IIT Delhi

30

Operator Overloading
class complex_num {
Modify meaning of +
private:
float real
real, imag;
operator for this type
public:
void set_r (float r);
void set_i
set i (float i);
complex_num operator+ (const complex_num &x) {
complex_num y;
y.reall = reall + x.real;
l
y.imag = imag + x.imag;
return y;
}...
};
int main () {
complex_num c (1.0, 1.0), d (2.0, 3.0), e;
e = c + d; // e = c.operator+ (d)
}
April 2016

(C) P. R. Panda, IIT Delhi

31

Designing a Class
Identify data members
How should objects be initialised?
design the constructors

How
H
to READ d
data members?
b ?
design member functions (mark them const)

How to modify objects?


design
g member functions ((expose
p
minimal details))

April 2016

(C) P. R. Panda, IIT Delhi

32

Designing a Class
What operations are relevant for this class?
provide them as separate functions
operators could be overloaded

Other:
how should objects be copied?
default
d f lt : member-wise
b
i copy ((as iin struct)
t t)

DESTRUCTORS (functions called when object is


destroyed)
default: do nothing

April 2016

(C) P. R. Panda, IIT Delhi

33

Vous aimerez peut-être aussi