Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
class
Objective is to define new object and define
new behavior
For example, birds flying action, withdrawing
money from ATM
It can be implemented in programming
language by putting built-in data type
together and defining new operations
Class Basics
User-defined data type
Consists of a set of members (data members &
member functions)
Data members store the state of the object
Member functions can define the initialization, copy,
move, behavior and cleanup
Members are accessed using . (dot) for objects and
-> (arrow) for pointers
Class is a namespace containing its members
Public members provide classs interface and private
members provide implementation details
Member Functions
In programming language implementing a
// representation
// data members
Date and
functions
struct Date {
int dd, mm, yy;
void init(int d, int m, int y); // initialize
void add_year(int n); // add n years
};
Member function
Date my_birthday;
void f() {
Date today;
today.init(16, 10,
1996);
my_birthday.init(30, 12,
1950);
Date tomorrow =
today;
tomorrow.add_day(1);
d = 16,
dd = 234556
mm =
87234901
yy = 19342
Address:
oxfacdbe2102
void Date::init(this = oxfacdbe2102,
m = 10, y = 1996)
{
dd = d;
// this is equal to
.
.
update_name(); //unqualified
Book::update_isbn(); //qualified
Access Control
Declaration of Date in example provides a set
global scope
d.dd = d.dd 200;
since timewrap
object to work on
of functions?
Yes, keep data members in private section
struct Date {
private:
int d, m, y;
public:
void init(int m, intd, int y);
void add_year(int n);
}
object
Member functions define interface to object
Private part can be used only by member
functions
Public part constitutes the public interface to
For
example,
objects
Non-member
functions can
void timewrap(Date
&d) {not access private
d.y = d.y 200;
//error: Date::y is private
member
member
of initializing members
Init() function can do this job
Date dx;
dx.mm = 3; // error
dx.init(25, 3, 2011); // OK
Is it convenient?
Every object declaration requires following init()
Object Initialization
Can we do better?
Yes, we can. Take the help of Constructor
Constructor is a method with explicit purpose
of initializing object
It is recognized by having the same name as
the class itself
For example,
struct Date {
private:
int m, d, y;
public:
Date();
Date(int mm, int
dd, int yy);
int main() {
Date now;
Date tomorrow(11, 3,
2016);
}
END