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

C++ - Object-Oriented Programming - Part1

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)
4 views

C++ - Object-Oriented Programming - Part1

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/ 57

C/C++ Programming Techniques

ET2031/ ET2031E
Chapter 5:
Object-Oriented Programming

Lecturer: PhD. DO Thi Ngoc Diep


SCHOOL OF ELECTRICAL AND ELECTRONIC ENGINEERING
HANOI UNIVERSITY OF SCIENCE AND TECHNOLOGY
Content

• 5.1. Introduction to C++


• 5.2. Overview of OOP
• 5.3. Class and Object in C++
• Constructors and Destructor
• Method and Property Members of Object
• Operator overloading

3
5.1. Introduction to C++

4
New features of C++ (compared to C)

• A hybrid programming language: functional and object-oriented


programming language
• adds object-oriented features: abstraction, encapsulation,
inheritance, polymorphism, etc.
• Overloading of functions/operators, functions with default
parameters, inline sub function
• Add new import/export classes
• Add new dynamic memory allocation and release functions, new
and delete.
• Add object, reference type parameters
• Generic programming (template)

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

• cin >> a >> b;


• string mystring;
cin >> mystring;
• #include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
return 0;
}

8
New features of C++ (compared to C)

• Dynamic memory allocation


• Can still use malloc()/free() as in C
• add operators new and new[] for allocation
int *a = new int;
float *b = new float(5.23f);
long *c = new long[5];
• add operators delete và delete[] for free
• delete a;
delete[] c;
• Note: malloc/free should not be confused with new/delete:
• Allocate with malloc(), must use free() to free
• Allocate with new, must use delete to free

9
New features of C++ (compared to C)

• Namespace: scope of variable, function, class (same name,


different name), to manage name conflicts of program elements
such as variable names, class names, function names, etc.
• namespace name { …. // class, variable, function …. }
• name::class ;
• using namespace name ; using name::class ;

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

• int & max(int &a, int &b) {


return (a > b? a: b);
}
int main()
{
int x = 5, y = 10; // int x = 5, y = 1;
cout << max(x, y) << endl;
10 // 5
max(x, y) = 7; 57 // 7 1
cout << x << ' ' << y;
return 0;
}

11
New features of C++ (compared to C)

• Passing a value to a function


• Functions in C:
• value-type parameters, created on call and destroyed when the function
terminates  has no effect on the caller.
• pointer type parameters: can change the value of the variable at the caller.
• In C++: in addition, can have reference type parameters
• Do not make copies of parameters: save memory, time
• Working directly on the memory of the reference variable

void foo(int &x) void exchange(int &a, int &b){


{ x = 2;} int c=a; a=b; b=c;
}
int y = 1;
foo(y); //  y = 2 int x=10, y=20;
cout<<"Before swap x="<<x<<",y="<<y<<endl;
exchange(x,y);
cout<<"After swap x="<<x<<",y="<<y<<endl;

12
Notes

Most C programs are also C++ programs.

Nevertheless, good C++ programs usually do not resemble C:


• avoid macros (use inline)
• avoid pointers (use references)
• avoid malloc and free (use new and delete)
• avoid arrays and char* (use vectors and strings) ...
• avoid structs (use classes)

C++ encourages a different style of programming:


• avoid procedural programming
• model your domain with classes and templates

13
5.2. Overview of OOP

14
Overview of OOP Technology

• Evolution of programming languages


Imperative Structural/ Object-
Machine language
programming Functional Oriented

• Functional vs. Object Oriented


• Structural/Functional oriented :
• data structures + algorithms (set of functions) = Program
• Object Oriented:
• objects + messages = Program

15
Overview of OOP Technology

• Object orientation is a technique of modeling a system into


multiple objects that interact with each other
• All element representations in a system are “objects”

House
Reality Tom Car Flower

Object-oriented modeling

drives Car
Model House lives in gets
Flower
Tom

16
Object definition ?

• Object in the real world is an entity that we can perceive normally


(see, touch, hear, etc.).
• It has states (attributes, properties) and behavior (operation)

Object State Behavior

- Speedometer: How fast is it - Move forward


moving? - Stop
- Odometer: How many miles has it - Reverse
driven? - ….
- ….
- Author: Who is the author? - Buy
- Pages number: How many pages - Borrow
does it contain ? - Count the number of
-… pages….

17
Object definition ?

• State of an object: the • Behavior determines how the


conditions in which the object object acts and responds to
exists. the outside world.
• State of an object can change • A set of messages that object
over the time. can respond to
(the operations that the
object performs).

18
Object

• The most basic component of an OOP, representing an object of


the problem
• Combination of data and the necessary processing operations on
those data of objects.
• Processing operations are also known as methods, or member functions
• Data is also known as properties, attributes

Circle A Rectangle C A Quadratic eq.

a = 3
Width a = 2
Radius r = 2 b = 4
Length b = 3
c = 1

Cal_Perimeter() Cal_Perimeter() Cal_Delta()


Cal_Area() Cal_Area() Cal_Solution()

19
Class

• Is a generalization of objects of the same type


• Similar to the data types of data object
• Allow to create multiple objects of the same type (same properties
and methods).

Circle Rectangle Quadratic eq.


a
Width a
Radius r b
Length b
c

Cal_Perimeter() Cal_Perimeter() Cal_Delta()


Cal_Area() Cal_Area() Cal_Solution()

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

• Objects are also called instances of a class


• Each instance of a class has its own instance attribute
Rectangle

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

• Objects in OOP communicate via messages:


• Message passing is the way to interact between objects
• One object can send a message to another object (message sender)
• The target object receives the message and responds to the message by
performing some actions (a method).

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

• Calling a function • Sending a message


• Locate the exact code • Ask a service from an object
block that will be executed • The receiving object is the
• There is only one one who decides what to do
implementation for one (not the sender)
named function • One object can have
• Function names can not be different implementations
duplicated for the same service

24
Interaction between objects

• When an object a invokes an operation m() of object b


 a transmits the message m to b: a wants to ask b to do something
• The operation m() that b implements will fulfill that request

25
5.3. Class and Object in C++

26
Define a new class

• Information required to define a class


• Name
• The class name should describe the object in the real world
• List of attributes
• Similar to variable declaration
• List of methods
• similar to function declaration

Name
Attributes declaration

Method declaration

27
Define a new class

#include <iostream> Class definition


class Circle {
private: Attributes/ Properties of the class
double r;
public:

Access void setR(double rr) { r = rr; }


modifier double Cal_Area() { return 3.14*r*r; } Methods of
double Cal_Perimeter() { return 3.14*2.*r; } the 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

• Basic operations for objects:


• Declaration: is the first operation to use an object
• Component accessing operator:
• using the "." for regular objects
• “->” for pointer-type objects
int main()
{
Circle c; //regular objects
c.setRadius(10);
// ...
Circle *pc = &c; //pointer-type objects
pc->setRadius(20);
// ...
}

30
Access modifiers

• Access specifiers/modifiers of class members: show “Who can


see/access”
• Public: The properties or methods are accessible from outside the class.
• available to everyone, can be accessed by other classes and functions
• Private (by default): limited access, in that class only through the own
class's methods  represents data hiding properties
• Protected: see later

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

• When an object is created  allocate the memory + assign initial


value to the properties
• Use constructor functions
• When finished  free all the memory allocated to the object
• Use destructor function

class X {
int x;
float xx;

public:
X() {}
~X() {}
void printInt() {}
void printFloat() {}
};

33
Constructor

• A special method of the class


• Called automatically when a new object is created
• Purpose: to allocate memory, initialize values ​for properties, etc.
• The compiler will allocate memory for the object, then will call the
constructor.
• Each class must contain at least one constructor
• Responsible for creating a new instance of the class
• The name of the constructor is the same as the name of the class
• Constructors have no return type, public access scope

Student
Student(String nstr, String astr){
name = nstr;
- name
address = astr;
- address
}

34
Constructor

• If developer defines constructor for the class:


• It is possible to define multiple constructors with different arguments
• If at least 1 constructor has been defined, all necessary constructors must be
present
• Can be defined inside /outside of the class
• If developer does not define any constructor for the class
• The compiler will provide a default one: without input parameters, only
allocates memory for the object, and does not assign values ​to properties

Student(String nstr, String astr){


name = nstr;
Student address = astr;
- name }
- address
Student(){ Student(){
name = “no name”; name = “”;
address = “no address”; address = “”;
} }

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.;}

// Use constructors // call no argument constructor


Cubic c1;
Cubic c2(); // warning ! unused function, no object
Cubic c4(1.23, 2.3, 5.6); // 3 arguments constructor
Cubic c5[3]; // no argument constructor x 3 times
Cubic c6(1.23, 2.3); // 2 arguments constructor

c1 = Cubic; // error – need an expression


c1 = Cubic(); // ok: create a Cubic object, copy to c1
c1 = Cubic(2.33); // error– no 1 argument constructor

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.;}

// Use constructors with new operator -> Heap allocation


Cubic *c5 = new Cubic; // no argument cons.
Cubic *c6 = new Cubic(); // no argument cons.
Cubic *c7 = new Cubic(3.22, 2.3, 5.6); // 3 arguments cons.
Cubic *c8 = new Cubic[3]; // no argument cons. x 3

Cubic *c9; //does not call constructor


c9 = new Cubic(4.0,5.0); // 2 arguments cons.
c5 = new Cubic[4]; // no argument cons. x 4

37
Initialization list

• Initialization list of the class properties: after the constructor


prototype
• class Person {
private:
string name;
int age;
public:
Person(const char* n): name(n) { ... }
Person(const char* n, int a): name(n), age(a) { ...}
...
};
• … the corresponding code …
• Person(const char* n) {
name = n; ...
}
Person(const char* n, int a) {
name = n;
age = a;...
}
• Required for constant or reference properties

38
Copy constructor (Hàm tạo sao chép)

• Initialize a new object from an existing object of that class.


class Circle {
double r;
public Circle(const Circle &c) { r = c.r; }
};

• Can use standard syntax and assignment syntax


Circle c1(2.5);
Circle c2 = c1, c3(c1);
• Note:
• Circle c2;
c2 = c1; //assignment, no copy constructor
• void func1(Circle c) { ... } /*create a temporary object c, copy
from c1 using the copy constructor*/
func1(c1);
• void func2(const Circle &c) { ... } /*don't call copy constructor*/
func2(c1);
If not built, the compiler will automatically create a default copy function
that copies all member properties from the old object to the new object.

39
Copy constructor

• So when need to write the copy constructor ?


• when object has pointer or reference type property
• If using the default copy constructor => point to the same memory area => 2 objects
are not created independently.
 Need to build a copy constructor, to create a new memory area for the pointer
property

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)

• Used for initializing an object from an existing variable/object of


different type
• class Circle { … } ;
class Ellipse {
...
Ellipse(const Circle& c) { rx = ry = c.r; }
};

Ellipse e1(c1); // use Cast constructor (explicitly) Circle -> Ellipse


e1 = c1; // use Cast constructor (implicitly) to convert an object
// Circle -> Ellipse then make the assignment
• Other cases:
• void func3(const Ellipse& e) { ... }
func3(c1); // use Cast constructor (implicitly)
• cout << ((Ellipse)c1).area(); // use Cast cons. (explicitly)

• add keyword "explicit" before the declaration of Cast constructor if it is restricted to


be used in implicit conversions.

42
Destructor (Hàm hủy)

• Only 1 destruction method, called automatically when the object is


destroyed (freeing memory, local variables when exiting the
function)
• Syntax: ~class_name()
• No input parameters, no return type, public access scope
• If no destructor is built, the compiler will provide a default destructor
• Need to build, when the object uses Heap memory
• class String {
private:
char *str;
public:
String(){ str = NULL; }
String(const char* s) {
str = new char[strlen(s)+1]; strcpy(str, s);
}
~String(){ if (str) delete str; }
...
};

43
Example

class Point { int main()


float _x, _y; {
public: Point p1;
Point(float x=0, float y=0){ Point p2(10);
_x=x; Point p3(20,20);
_y=y; cout<<"D12="<<p1.distanceTo(p2)<<endl;
cout<<“Call constructor”<<endl; cout<<"D23="<<p2.distanceTo(p3)<<endl;
} cout<<"End of main" << endl;
Point (Point &p){ return EXIT_SUCCESS;
cout<<“Call copy const.”<<endl; }
_x = p._x; _y = p._y;
}
~Point(){ Call constructor
cout<<“Call destructor”<<endl; Call constructor
} Call constructor
float getX(){ return _x; } D12=Call copy const.
float getY(){ return _y; } 10
float distanceTo(Point p);
}; Call destructor
D23=Call copy const.
float Point::distanceTo(Point p){
float d = (p._x-_x)*(p._x-_x) 22.3607
+ (p._y-_y)*(p._y-_y); Call destructor
return sqrt(d); End of main
}
Call destructor
Call destructor
Call destructor

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

• A conceptual process : describe general information / properties/


features of objects.
• Focus on the basic features of an entity, features that distinguish
one entity from other entities.
• Depends on the viewing angle
• Some properties could be important in certain situation but not necessary in other
situations

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

• Hide the inside implementation details


• Provide an interface to the outside world
• Usage is unaffected by internal details (Users don't have to care
about the execution inside an object).

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

You might also like