Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
Miri Ben-Nissan (Kopel)
(2017)
©Miri Kopel, Bar-Ilan University 2
Attributes: • 4 bytes.• Integer numbers.
set of operations
attributes
Operations: • numerical operators• logical operations• bit operations• I/O operations
int
Data Types define the
way you use storage
(memory) in the
programs you write.
▪ How should we describe a car?
©Miri Kopel, Bar-Ilan University
3
engine
door
window
wheel
attributes
operations
A data type (int, float etc.) is characterized by:
(1) A set of values – that can be assumed by objects of the type.
(2) A set of operations – that can be performed on objects of the type.
Abstract Data Type (ADT) = user defined data type.
©Miri Kopel, Bar-Ilan University 4
▪ADT = packaging data with functions to create a new data type. This is also called encapsulation.
▪Built-in types: int, bool, float.
▪User-defined types: stacks, queue, tree, student, text-editor.
▪ADT interfaces provide a list of operations (“what”) rather than an implementation description (“how”).
©Miri Kopel, Bar-Ilan University 5
©Miri Kopel, Bar-Ilan University 6
Car
iNum_Of_Doors;
iYear_Of_Manufacturing;
bIs_Automatic;
turnOn();
lock();
ADT
=
Car
▪ In C++ we use classes for defining ADTs.
▪The syntax:class ClassName
{
//attributes and operations
};
▪Objects are instances of classes. That is, objects are to classes what variables are to types.
▪A class definition does not allocate storage for anyobjects.
©Miri Kopel, Bar-Ilan University 7
©Miri Kopel, Bar-Ilan University 8
Example of Object Oriented Analysis
• N elevators for M floors.
• Every elevator has M buttons.
©Miri Kopel, Bar-Ilan University 9
• When pushing a button in the elevator:
• button is lighted.
• elevator arrives.
• doors are opened and button is turns off.
• On every floor, except first and last floors, there are two
buttons (up & down).
• When pushing a button on a floor:
• button is lighted.
• when the elevator arrives – the doors open and the
button’s light turns off.
• After a delay, the doors get closed, and the elevator
moves to the requested way (if there are any requests).
• When there are no requests for the elevator – it parks in
the current floor with closed doors.
©Miri Kopel, Bar-Ilan University 10
elevator
button
floor
button
elevator
button
1 2
3 4
5 6
7 8
door
floor
MethodMessage How to do
What todo
2 uses of class functions:
#include <iostream>
class Point
{
public:
int x,y;
void Show () { std::cout<<"x="<<x<<" y="<<y<<std::endl; }
};
int main ()
{
Point p;
p.x=15;
p.y=10;
p.Show ();
std::cout<<"Please enter x and y values: ";
std::cin >> p.x >> p.y;
p.Show ();
} ©Miri Kopel, Bar-Ilan University 11
▪The users of the class can clearly see exactly whatthey can use and what to ignore.
▪The ability to ensure that no client programmerbecomes dependent on any part the underlyingimplementation of a class.
▪public = all member declarations that follows areavailable to everyone.
▪private = no one can access that member exceptthe creator of the type inside function members ofthat type. It’s a brick wall between the object andthe client programmer.
©Miri Kopel, Bar-Ilan University
12
class MyClass
{
public:
//Data and methods accessible to any user of
//the class.
protected:
//Data and methods accessible to class
//methods, derived classes, and friends only.
private:
//Data and methods accessible to class
//methods and friends only.
};
©Miri Kopel, Bar-Ilan University 13
©Miri Kopel, Bar-Ilan University 14
#include <iostream>
class Point
{
private:
int m_x, m_y;
public:
void Set_x(int val) { m_x=val; }
int Get_x() {return m_x; }
void Set_y(int val) { m_y=val; }
int Get_y(){return m_y; }
void Show(){std::cout<<"x="<<m_x<<
" y="<<m_y<<std::endl;}
};
©Miri Kopel, Bar-Ilan University 15
int main ()
{
Point p;
//p.m_x=15; -----ERROR
p.Set_x (15);
//p.m_y=10; -----ERROR
p.Set_y (10);
p.Show ();
p.Set_x (17);
p.Set_y (5);
std::cout<<"x= "<< p.Get_x() <<" y= “
<<p.Get_y()<<std::endl;
}
Example 2 (cont.):
©Miri Kopel, Bar-Ilan University 16
#include <iostream>
#include “Point.h”
class Line
{
private:
Point m_p1, m_p2; //composition
public:
void SetLine(int x1,int y1,int x2,int y2);
void SetLine(const Point& p1,const Point& p2);
void Show();
};
CompositionData members may be objects of built-in types as well as user-defined types.
Example 3:
©Miri Kopel, Bar-Ilan University 17
void Line::SetLine(int x1,int y1,int x2,int y2)
{
m_p1.Set_x(x1);
m_p1.Set_y(y1);
m_p2.Set_x(x2);
m_p2.Set_y(y2);
}
void Line::SetLine(const Point& p1,const Point& p2)
{
m_p1 = p1; //operator = between 2 Points
m_p2 = p2;
}
void Line::Show()
{
std::cout<<"Line from: "; m_p1.Show();
std::cout<<" To: "; m_p2.Show();
}
©Miri Kopel, Bar-Ilan University 18
int main ()
{
Point p1,p2;
p1.Set_x(15); p1.Set_y(10);
p2.Set_x(0); p2.Set_y(0);
Line line1,line2;
line1.SetLine(15,10,7,6);
line1.Show();
line2.SetLine(p1,p2);
line2.Show();
}
Line from: x=15 y=10
To: x=7 y=6
Line from: x=15 y=10
To: x=0 y=0
▪In C we have macro:
#define SUM(X,Y) ((X)+(Y))▪ Implemented by the pre-processor.
▪An inline function is a function whose code gets inserted into the caller's code stream.▪ Like a #define macro, inline functions improve
performance by avoiding the overhead of the call itself and (especially!) by the compiler being able to optimize throughthe call ("procedural integration").
©Miri Kopel, Bar-Ilan University 19
▪To define an inline function, you must ordinarily precede the function definition with the “inline” keyword.
▪It is not necessary inside a class definition.▪A member function defined within the class
definition is taken automatically to be an inline member function.
▪That is, in-class definition of member functions is for small, frequently-used functions.
©Miri Kopel, Bar-Ilan University 20
inline functions (cont.):
▪An inline is just a suggestion to the compiler.▪ When the function is too complicated the compiler may
reject the inline request.
▪ When the compiler must produce an address of the function, it will always reject our request.
▪Constructors and Destructors may have hidden activities inside them since the class can contain sub-objects whose constructors and destructors must be called.▪ You should consider its efficiency before making them
inline.
©Miri Kopel, Bar-Ilan University 21
inline functions (cont.):
▪Since the inline mechanism is done by the compiler (before the linkage), it's usually imperative that the function's definition (the part between the {...}) be placed in a header file. ▪ If you put the inline function's definition into a .cpp file, and if
it is called from some other .cpp file, you'll get an "unresolved external" error from the linker.
▪ You should consider the information hiding subject in this case.
▪Beware that overuse of inline functions can cause code bloat, which can in turn have a negative performance impact in paging environments.
©Miri Kopel, Bar-Ilan University 22
inline functions (cont.):
▪The class designer can guarantee initialization of every object by providing a special function, called the constructor. ▪ If a class has a constructor, the compiler
automatically calls that constructor at the point an object is created.
▪The name of the constructor is the same as the name of the class.
▪Like any function, the constructor can have arguments to allow us to specify how an object is created, give it initialization values, and so on.
©Miri Kopel, Bar-Ilan University 23
▪The destructor is guarantee for cleaning up the object.▪ It is called automatically be the compiler when
the object goes out of scope.
▪The syntax for the destructor is similar to that for the constructor: the class name with a leading ~.
▪The destructor never has any arguments because destruction never needs any options.
▪Both the constructor and the destructor have no return values.
©Miri Kopel, Bar-Ilan University 24
▪A default constructor is one that can be called with no arguments. ▪The default constructor is so important that if
(and only if) there are no constructors for a class, the compiler will automatically create one for you.
©Miri Kopel, Bar-Ilan University 25
If I declared
other Ctor in the
class, do I get the
Default one too?
©Miri Kopel, Bar-Ilan University
26
#include <iostream>
using namespace std;
class Point
{
private:
int m_x, m_y;
public:
Point () {m_x=0; m_y=0;} //default constructor
Point (int valX, int valY) {m_x=valX; m_y=valY;}
~Point () {cout<<"GoodBye"<<endl;} //destructor
void set_x (int val) { m_x=val; }
int get_x () {return m_x; }
void set_y (int val) { m_y=val; }
int get_y () {return m_y; }
void show (){cout<<"x="<<m_x<<" y="<<m_y<<endl; }
};
©Miri Kopel, Bar-Ilan University 27
Example 3 (cont.):
int main ()
{
Point p1 (15,10);
Point p2; //default point
std::cout<<"The first point - ";
p1.show();
std::cout<<"The second point - ";
p2.show();
}
The first point - x=15 y=10
The second point - x=0 y=0
GoodBye
GoodBye
©Miri Kopel, Bar-Ilan University
28
class Point
{
private:
int m_X, m_Y;
public:
Point();
Point(int x, int y);
~Point(){std::cout<<"Deleting a point...\n";}
//the set & get methods as before...
};
Point::Point() //default constructor
{ std::cout<<“Creating a default point…\n";
m_X=0; m_Y=0;
}
Point::Point(int x, int y) //constructor with args
{ std::cout<<"Creating a point...\n";
m_X=x; m_Y=y;
}
Example 5:
©Miri Kopel, Bar-Ilan University
29
class Line
{
private:
Point m_p1, m_p2;
public:
Line(){std::cout<<"Creating a default line...\n";};
Line(int x1,int y1,int x2,int y2);
~Line() {std::cout<<"Deleting a line...\n";}
};
Line::Line(int x1,int y1,int x2,int y2)
{
std::cout<<"Creating a line...\n";
//set the x and y values of p1 and p2
//with the arguments x1,y1,x2,y2.
//...
}
©Miri Kopel, Bar-Ilan University 30
int main()
{
Line l1;
Line l2(2,5,7,8);
}
Line l1
Point m_p1
int m_X
int m_Y
Point m_p2
int m_X
int m_Y
Line l2
=0
=0
=0
=0
Creating a default point...
Creating a default point...
Creating a default line...
Creating a default point...
Creating a default point...
Creating a line...
Deleting a line...
Deleting a point...
Deleting a point...
Deleting a line...
Deleting a point...
Deleting a point...
Point m_p1
int m_X
int m_Y
Point m_p2
int m_X
int m_Y
=0
=0
=0
=0
=2
=5
=7
=8
▪In composition, the constructors are called in the following order:▪ Internal object’s constructor.
▪External class’s constructor.
▪The destructors are called in the reversed order.
©Miri Kopel, Bar-Ilan University 31
▪Data members may be object of built-in types as well as user-defined types.
▪When an object is created, the compiler guarantees that constructors for all of its sub-objects are called. ▪ In case all the sub-objects have default
constructors, this is what the compiler automatically calls.
▪QUESTION: How do we initialize class data members that are objects of user-defined types whose constructors require arguments?
©Miri Kopel, Bar-Ilan University
32
▪ANSWER:Use the member initialization section.▪That is the part of the constructor after the ‘:’ following the constructor’s parameter list (up to the first ‘{‘).
▪It’s a good habit to always use the member initialization section.
▪Member initialization section only applies to constructors.
©Miri Kopel, Bar-Ilan University 33
©Miri Kopel, Bar-Ilan University 34
class Line
{
private:
Point m_p1,m_p2;
public:
Line(int x1, int y1, int x2, int y2);
~Line(); //destructor
double Length ();
void SetLine (int x1,int x2,int y1,int y2);
void Show ();
};
©Miri Kopel, Bar-Ilan University
35
//~~~~~~~~~~~~~~~~~~~~~~~~
// Constructor with initialization list
//~~~~~~~~~~~~~~~~~~~~~~~~
Line::Line(int x1,int y1,int x2,int y2)
: m_p1(x1,y1), m_p2(x2,y2)
{ }//~~~~~~~~~~~~~~~~~~~~~~~~
// Destructor
//~~~~~~~~~~~~~~~~~~~~~~~~
Line::~Line( )
{
cout<<"See you again soon!\n";
}//~~~~~~~~~~~~~~~~~~~~~~~~
// Length
//~~~~~~~~~~~~~~~~~~~~~~~~
double Line::Length ()
{
return sqrt(pow(m_p1.Get_x()-m_p2.Get_x(),2) +
pow(m_p1.Get_y()-m_p2.Get_y(),2));
}
©Miri Kopel, Bar-Ilan University 36
void Line::SetLine (int x1,int x2,int y1,int y2)
{
m_p1.Set_x(x1); m_p1.Set_y(y1);
m_p2.Set_x(x2); m_p2.Set_y(y2);
}
void Line::Show()
{
std::cout<<"The first point - ";
m_p1.Show(); cout<<std::endl;
std::cout<<"The second point - ";
m_p2.Show(); cout<<std::endl;
}
©Miri Kopel, Bar-Ilan University
37
int main ()
{
Point p(15,10);
p.Show();
Line l(2,90,16,1);
l.Show();
std::cout<<"l's length is - “
<<l.Length()<<std::endl;
}
x=15 y=10
The first point - x=2 y=90
The second point - x=16 y=1
l's length is - 90.0944
See you again soon!
GoodBye
GoodBye
GoodBye
©Miri Kopel, Bar-Ilan University 38
Stack
Code Segment
Global Data Segment
Heap
©Miri Kopel, Bar-Ilan University 39
int f(int x, char c);
int g = f(a,b);
Handling passing and returning variables by
value during function calls:
push b
push a
call f()
add sp, 4
mov g , register a
Function arguments
Return address
Local variables
▪When you pass an object by value, you create a new object (the passed object inside the function frame) from an existing object (the original object outside the function frame). This is also true when returning an object by value.
▪The compiler’s assumption is that you want to perform this creation using a bitcopy.
©Miri Kopel, Bar-Ilan University 40
object_1 object_2
m_pArray
1024m_pArray
1024
1024
▪In order to prevent the compiler from doing a bitcopy, you define your own function to be used whenever the compiler needs to make a new object from an existing object. This function is called copy constructor.
▪The single argument to this constructor has to do with the object you’re constructing from.
▪The object can’t be passed into the constructor by value, because you’re trying to define the function that handles passing by value
©Miri Kopel, Bar-Ilan University 41
©Miri Kopel, Bar-Ilan University
42
class String
{
private:
char* m_str;
//...
public:
String(const char* str=NULL);
String(const String& str); //copy constructor
~String();
//...
};
String::String(const String& str)
{ //str cannot be NULL since it’s passed by reference
m_str = new char[strlen(str.m_str)+1];
strcpy(m_str,str.m_str);
}
Example 7:
If I declare a
C.Ctor only,
do I get also
the Default
Ctor?
In some cases, it is necessary for the compiler to create temporary objects. These temporary
objects can be created for the following reasons:▪Result of expression evaluation.
▪Result of expressions using the built-in (not overloaded) logical operators (|| and &&).
▪ Initializing const references.
▪To store the result of a cast to a user-defined type.
▪To store the return value of a function that returns a user-defined type.
©Miri Kopel, Bar-Ilan University 43
▪Temporary objects have a lifetime that is defined by their point of creation and the point at which they are
destroyed.
class MyString
{
public:
MyString(const char* str=NULL);
~MyString();
private:
char* m_str;
};
©Miri Kopel, Bar-Ilan University
44
Example 8:
©Miri Kopel, Bar-Ilan University
45
MyString::MyString(const char* str1/*=NULL*/)
{
std::cout<<"creating a string\n";
if(str1){
m_str = new char[strlen(str1)+1];
strcpy(m_str,str1);
}
else{
m_str = NULL;
}
}
MyString::~MyString()
{
if(m_str){
delete[] m_str;
m_str = NULL;
}
std::cout<<"deleting a string\n";
}
©Miri Kopel, Bar-Ilan University 46
MyString GetString()
{
MyString str2("testing");
return str2;
}
int main()
{
MyString str3( GetString() );
}
main() GetString()
str2temp
m_str
str3