C++ - Object-Oriented Programming - Part1
C++ - Object-Oriented Programming - Part1
ET2031/ ET2031E
Chapter 5:
Object-Oriented Programming
3
5.1. Introduction to C++
4
New features of C++ (compared to C)
5
New features of C++ (compared to C)
• Some changes :
• The source code file : .cpp extension
• Add Boolean type (false and true values):
bool b1 = true, b2 = false;
• Variables and constants in C++ can be declared anywhere in the
function
• Type conversion can be written: type(expression)
int(5.32)
• No need to add enum, struct, and union keywords when declaring
variables
• etc.
6
First C++ Program
• Example program:
• #include <iostream>
void main() {
int n;
cout << “Input n: ";
cin >> n;
cout << "n = " << n << endl;
}
• Input/output with C++
• iostream.h library: standard input and output streams
• cout << expression<< expression …; : used to print to stdout (screen)
• cin >> variable >> variable …; : used to read data from stdin (keyboard)
• cerr << "An error occured"; : used to print to stderr (screen)
• iomanip.h library: set format for stream: setw, setprecision, etc.
• fstream library: working with files
cout << endl : Inserts a new line and flushes the stream
cout << "\n" : Only inserts a new line.
7
Examples
8
New features of C++ (compared to C)
9
New features of C++ (compared to C)
10
New features of C++ (compared to C)
• Reference variable
• no memory allocation, no private address
• used as an alias for a certain variable
• used to access the memory of this variable (pointer)
• commonly used as function parameters to perform parameter passing
• int a = 5;
int &b = a; // must be initialized
b = 10; // shared memory a = 10
11
New features of C++ (compared to C)
12
Notes
13
5.2. Overview of OOP
14
Overview of OOP Technology
15
Overview of OOP Technology
House
Reality Tom Car Flower
Object-oriented modeling
drives Car
Model House lives in gets
Flower
Tom
16
Object definition ?
17
Object definition ?
18
Object
a = 3
Width a = 2
Radius r = 2 b = 4
Length b = 3
c = 1
19
Class
20
Class
In OOP:
1. All things are objects
2. Each object has specific attributes (state) that form Class of
objects
3. Each object in the program has its own independent
attribute value and takes up its own memory
4. All objects belonging to the same class have the same
methods (behavior)
5. A software program can be considered as a set of objects
that interact with each other through object methods
21
Relationship between object and class
Width a
Length b
Cal_Perimeter()
Cal_Area()
Rectangle A Rectangle B
Width a = 1 Width a = 3
Length b = 2 Length b = 4
Cal_Perimeter() Cal_Perimeter()
Cal_Area() Cal_Area()
22
Interaction between objects
Message Method
• is a signal sent from one object to • Procedure/Function in structure
another programming
• not include the implementation code • is an implementation code block
block corresponding to each message
sent to object
23
Interaction between objects
24
Interaction between objects
25
5.3. Class and Object in C++
26
Define a new class
Name
Attributes declaration
Method declaration
27
Define a new class
28
Using objects
#include <iostream>
class Circle {
private:
double r;
public:
void setR(double rr) { r = rr; }
double Cal_Area() { return 3.14*r*r; }
double Cal_Perimeter() { return 3.14*2.*r; }
};
void main() {
Circle c; Objects
Object usage
c.setR(1.23);
std::cout << “Area: " << c.Cal_Area () << std::endl
<< "Perimeter: " << c.Cal_Perimeter() << std::endl;
}
29
Using objects
30
Access modifiers
class Box {
// in the main()
public:
Box box;
double length; box.length = 10.0; // OK
void setWidth( double wid ){width = wid;}; box.width = 10.0; // Error
double getWidth(){return width;}; box.setWidth(10.0); // OK
private:
double width;
};
31
Object Initialization
• Each object is allocated a memory area to store the values of the
component data
• copy of all the class data members (properties)
• code for functions is stored once in memory for each class in code/text
segment memory part
class X {
int x;
float xx;
public:
X() {}
~X() {}
void printInt() {}
void printFloat() {}
};
32
Object Initialization
class X {
int x;
float xx;
public:
X() {}
~X() {}
void printInt() {}
void printFloat() {}
};
33
Constructor
Student
Student(String nstr, String astr){
name = nstr;
- name
address = astr;
- address
}
34
Constructor
35
Example
• class Cubic {
double x, y, z ;
public:
// user-defined constructor, no argument
Cubic() { x = y = z = 0.; }
// user-defined constructor, 3 arguments
Cubic(double u, double v, double t){ x=u; y=v; z=t;}
// user-defined constructor, 2 arguments, outside of class
Cubic(double u, double v);
};
Cubic::Cubic(double u, double v){x=u; y=v; z=0.;}
36
Example
• class Cubic {
double x, y, z ;
public:
// user-defined constructor, no argument
Cubic() { x = y = z = 0.; }
// user-defined constructor, 3 arguments
Cubic(double u, double v, double t){ x=u; y=v; z=t;}
// user-defined constructor, 2 arguments, outside of class
Cubic(double u, double v);
};
Cubic::Cubic(double u, double v){x=u; y=v; z=0.;}
37
Initialization list
38
Copy constructor (Hàm tạo sao chép)
39
Copy constructor
class HD { c1(3)
private: int r; double *a; r=3
public: *a
HD(int x){
r=x; a=new double[x];
for (int i=0;i<x;i++)a[i]=0; 0 0 0
c2(c1)
}
r=c1.r
}; *a=c1.a
HD c1(3);
HD c2(c1);
// call default copy constructor
// c2.r = c1.r; c2.a = c1.a = address of the same memory area
40
Copy constructor
class HD { c1(3)
private: int r; double *a; r=3
public:
HD(int x){ *a
r=x; a=new double[x];
for (int i=0;i<x;i++)a[i]=0; 0 0 0
} c2(c1)
HD(const HD &c) { r=c1.r ≠
r = c.r; a = new double[c.r];
*a
for (int i=0;i<c.r;i++)a[i]=c.a[i]; 0 0 0
}
};
HD c1(3);
HD c2(c1); // call user-defined copy constructor
41
Cast constructor (Hàm tạo chuyển kiểu)
42
Destructor (Hàm hủy)
43
Example
44
“this” pointer
• A pointer to the object being called itself, scoped only within the
methods of the class.
• Used when:
• Local variables have the same name as property name
• Needed when referring to the address of the object being called
class Buffer;
void do_smth(Buffer* buf);
class Buffer { Buffer buf(4096);
private: buf.some_method();
char* b; int n;
public:
Buffer(int n)
{ this->n = n; this->b = new char[n];
}
~Buffer()
{ delete this->b; }
Red: can be removed
void some_method()
Blue: must have
{ do_smth(this); }
};
45
Understand the principles of OOT
46
Fundamental principles of OOT
Object-Oriented Technology
Polymorphism
Encapsulation
Abstraction
Inheritance
47
Abstraction
48
Understand the principles of OOT
• Data abstraction:
• Describe data in different ways depending on the problem
• To distinguish different entities in that context
• Class is the result of data abstraction
• Class is a conceptual model, describing the entities
• A class is an abstraction of a set of objects
• Attribute are also abstract
49
Encapsulation
50
Understand the principles of OOT
• Encapsulation:
• Data/attributes and behaviors/methods are packaged in a class
Example: Bicycle
Methods
51
Understand the principles of OOT
• Encapsulation:
• An object is an entity encapsulated with the purpose:
• Provides set of certain services
• The encapsulated object can be seen as a black box - the jobs inside are
hidden from the client
• Although the design/source code inside is changed, the external interface
is not changed
Input Output
Object
52
Understand the principles of OOT
• Encapsulation:
• Once encapsulated, an object has two views:
• Inside: Details of the properties and methods of the class
• Outside: Services that an object can provide and interact with the rest of the
system
• Access specifier/modifier
• determines the visibility of a Client Methods
member to the others
• private property or method : Inside only
• public property or method : Open for outside Data
• By default: members have private modifier
53
Understand the principles of OOT
• Data hiding
• Use access modifiers to hide data: avoid unauthorized changes or
falsification of data
• The data is hidden inside the class by assigning private access modifier
• Other objects that want to access this private data must go through the
methods of the class that have public access modifier
54
Understand the principles of OOT
• Data hiding
• In order to access and modify data values, the class can provide public
services/ methods
• Accessor (getter): Returns the current value of an property (data)
• Mutator (setter): Change the value of an property
• Usually getX and setX, where X is the property name
class Circle {
private:
static const float PI=3.1415; void main() {
float r; Circle c;
public: c.setRadius(15.5); //OK
void setRadius(float re){ c.r = 10; //Error
if(re < 0 ) { … } cout<<“R =”<<c.getRadius();
else { r=re; } };
}
float getRadius(){
return r;
}
float area(){
return PI*r*r;
}
};
55
Bài tập
1. Viết một lớp String để đóng gói kiểu chuỗi char* và các phương thức cần
thiết: khởi tạo String, khởi tạo sao chép String, thay đổi nội dung đối tượng
String hiện tại bằng nội dung của một đối tượng String khác, ghép nội dung
một đối tượng String khác vào sau đối tượng String hiện tại.
2. Viết lớp Fraction (phân số) với những phương thức: khởi tạo, khởi tạo sao
chép, các phương thức thực hiện phép cộng/ trừ/ nhân/ chia với 1 phân số
khác.
3. Viết lớp Square và lớp Rectangular (là lớp bạn của lớp Square). Viết phương
thức khởi tạo, khởi tạo sao chép, phương thức tính diện tích, tính chu vi của
2 lớp.
4. Viết lớp Vector 3 thành phần với những phương thức cần thiết: khởi tạo,
khởi tạo sao chép, cộng/trừ vector, nhân với 1 hằng số, nhân vô hướng 2
vector, đếm số Vector hiện có.
56
Exercises
1. Write a String class to encapsulate the string type char* and the necessary
methods: string initialization, string copy, string concatenation.
2. Write a Fraction (fraction) class with methods: initialize, copy constructor,
perform addition/subtraction/multiplication/division with another fraction.
3. Write the Square class and the Rectangular class (which is a friend of the
Square class). Write a method to initialize, calculate the area, calculate the
perimeter in these 2 classes.
4. Write a 3-component Vector class with the necessary methods: initialize,
copy, add/subtract vectors, multiply by 1 constant, scalar multiply 2 vectors,
count the number of existing Vectors.
57