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

05 BasicOOP

The document outlines the key concepts of object-oriented programming in C++ including classes, objects, access specifiers, constructors, destructors, operator overloading, and more. It provides examples of declaring and defining classes, creating objects, using access specifiers, overloading operators, and more. The document is a lecture on basic OOP concepts in C++ for computer science students.

Uploaded by

Hoàng Ngân
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

05 BasicOOP

The document outlines the key concepts of object-oriented programming in C++ including classes, objects, access specifiers, constructors, destructors, operator overloading, and more. It provides examples of declaring and defining classes, creating objects, using access specifiers, overloading operators, and more. The document is a lecture on basic OOP concepts in C++ for computer science students.

Uploaded by

Hoàng Ngân
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Hochiminh City University of Technology

Computer Science and Engineering


OOP in C++

Basic OOP Lecturer: Vu Van Tien

1
Today’s outline
❖ Concept and Definition of Class ❖ Nested Class
❖ Access Specifier ❖ Shallow Copy & Deep Copy
❖ Constructor/Destructor ❖ Assignment Operator
❖ Operator Overloading ❖ Copy Constructor
❖ Friendship

2
Class
Structure versus Object-Oriented Programming
❖ Structure programming focuses on the process/actions that occur in a
program. The program starts at the beginning, does something, and ends.

❖ Object-Oriented programming is based on the data and the functions that


operate on it. Objects are instances of abstract data types that represent the
data and its functions

4
Limitations of Structure Programming
❖ If the data structures change, many functions must also be changed

❖ Programs that are based on complex function hierarchies are:


❖ difficult to understand and maintain
❖ difficult to modify and extend
❖ easy to break

5
Class

6
Class
❖ Class: a user defined datatype which groups together related pieces of
information
❖ Data
❖ Functions (Methods)
❖ Classes are similar to Structure but contain functions, as well.

7
Terminologies
❖ Object is an instant of a particular class
❖ Data are known as fields, members, attributes, or properties
❖ Functions are known as methods

8
Classes and Objects
❖ A Class is like a blueprint and objects are like houses built from the blueprint

9
Class Declaration

class <Class_Name>
{
<access_specifier>:
member declaration;
...
<access_specifier>:
member declaration;
...
};

10
Class Example
class Rectangle
{
private:
double width;
double height;
public:
void setWidth(double);
void setHeight(double);
double getWidth();
double getHeight();
double getArea();
};
11
Class Access specifier
❖ Used to control access to members of the class:
❖ private (default) : the members declared as private are only accessible from
within the class. No outside Access is allowed.
❖ public: the members declared as public are accessible from outside the
Class through an object of the class.
❖ Can be listed in any order in a class
❖ Can appear multiple times in a class

12
Member Function Definition
❖ When defining a member function:
❖ Put prototype in class declaration
❖ Define function using class name and scope resolution operator (::)

void Rectangle::setWidth(double w)
{
width = w;
}

13
Set and Get
❖ Set (mutator): a member function that stores a value in a private member
variable, or changes its value in some way.
void setWidth(double);
void setHeight(double);

❖ Get (accessor): a member function that retrieves a value from a private


member variable.
double getWidth();
double getHeight();

15
Using const With Member Functions
❖ const appearing after the parentheses in a member function declaration
specifies that the function will not change any data in the calling object.
❖ Example

double getWidth() const;


double getHeight() const;
double getArea() const;

16
Scope operator
❖ Scope operator ::
❖ Is used in the definition of member function outside the class
❖ Inline function vs. normal function
❖ Member functions defined in the class definition is considered as inline
function.

17
Constructor vs Destructor

1
Constructor
❖ Constructors: a special function that is automatically called whenever a new
object is created .
❖ allow the class to initialize member variables or allocate storage.
❖ do not return a value, including void.
❖ can not be called explicitly as member functions.

20
Default Constructor
❖ A default constructor is a constructor that takes no arguments.
❖ If you write a class with no constructor at all, C++ will write a default
constructor for you, one that does nothing.
❖ A simple instantiation of a class (with no arguments) calls the default
constructor:
Rectangle r;

21
Constructor Syntax

class <Class_Name>
{
...
public:
<Class_Name>();
...
};

22
Constructors with Parameters
❖ To create a constructor that takes arguments:
❖ Indicate parameters in prototype:
Rectangle(double , double );
❖ Use parameters in the definition:
Rectangle::Rectangle(double w, double h)
{
width = w;
height = h;
}

❖ You can pass arguments to the constructor when you create an object:
Rectangle r2(6, 4);

23
More About Default Constructors
❖ If all of a constructor's parameters have default arguments, then it is a default
constructor. For example:

Rectangle(double = 0, double = 0);

❖ Creating an object and passing no arguments will cause this constructor to


execute:

Rectangle r;

24
Overloading Constructors
❖ A class can have more than one constructor. They can be overloaded.
❖ The compiler automatically call the one whose parameters match the
arguments.
Rectangle();
Rectangle(double);
Rectangle(double, double);

25
Destructor
❖ Destructor: responsible for the necessary cleanup of a class when lifetime of
an object ends.
❖ Destructors cannot:
❖ return a value
❖ accept parameters
❖ Destructors must have the same name as the class.
❖ Only one destructor per class, i.e., it cannot be overloaded
❖ If constructor allocates dynamic memory, destructor should release it

26
Destructor Syntax

class <Class_Name>
{
...
public:
~<Class_Name>();
...
};

27
Using Private Member Functions
❖ A private member function can only be called by another member function
❖ It is used for internal processing by the class, not for use outside of the class
❖ Example: If you wrote a class that had a public sort function and needed a
function to swap two elements, you’d make that private

28
Arrays of Objects
❖ Objects can be the elements of an array:

Rectangle rooms[8];

❖ Default constructor for object is used when array is defined

29
Arrays of Objects
❖ Must use initializer list to invoke constructor that takes arguments:

Rectangle rectArray[3]={Rectangle(2.1,3.2),
Rectangle(4.1, 9.9),
Rectangle(11.2, 31.4)};

30
Accessing Objects in an Array
❖ Objects in an array are referenced using subscripts

❖ Member functions are referenced using dot notation:

rectArray[1].setWidth(11.3);
cout << rectrArray[1].getArea();

31
Pointer to Class
❖ Objects can also be pointed by pointers. Class is a valid type.
❖ Class pointers is similar to struct pointers.
❖ E.g.:

Rectangle r2(6, 4);


Rectangle* r3 = &r2;
cout << r3->getArea() << endl;
cout << (*r3).getArea() << endl;

32
Using the this Pointer
❖ Every object has access to its own address through a pointer called this (a
C++ keyword)

void Rectangle::setWidth(double width)


{
this->width = width;
}

33
Operator overloading

3
Fundamentals of Operator Overloading
• Overloading an operator
–Write function definition as normal
–Function name is keyword operator followed by the symbol for the operator being
overloaded
–operator+ used to overload the addition operator (+)
• Using operators
–To use an operator on a class object it must be overloaded unless the assignment
operator(=)or the address operator(&)
•Assignment operator by default performs memberwise assignment
•Address operator (&) by default returns the address of an object

35
Restrictions on Operator Overloading
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]

Operators that cannot be overloaded


. .* :: ?: sizeof

36
Restrictions on Operator Overloading
• Overloading restrictions
–Precedence of an operator cannot be changed
–Associativity of an operator cannot be changed
–Arity (number of operands) cannot be changed
• Unary operators remain unary, and binary operators remain binary
• Operators &, *, + and - each have unary and binary versions
• Unary and binary versions can be overloaded separately
• No new operators can be created
–Use only existing operators
• No overloading operators for built-in types
–Cannot change how two integers are added
–Produces a syntax error

37
Operator Overloading

*As non-member function: a friend function of class

Reference: operator overloading - cppreference.com


38
Friendship

3
Friendship
❖ Friends are functions or classes declared with the friend keyword.
❖ Using friend functions can enhance performance.

40
Friend function member
❖ A non-member function can access private and protected members of class if
it is declared as a friend of class.
❖ E.g.:
class Student {

❖ . . .
public:
friend Student duplicateStudent(Student& a);
};

41
Friend class
❖ Friend class: is a class whose members can access to private and protected
members of other classes.
❖ class Lecturer;
class Student {
friend class Lecturer;// lecturer is a friend
. . .
};

42
Nested Class
Nested class
❖ Nested class: Class declared within another class

Nested class

44
Nested class –Why?
❖ Avoid name conflicts while assisting the implementation of enclosed class

45
Shallow vs Deep Copy
Shallow Copy
❖ Shallow copy: two or more pointers of the same type point to the same
memory

second = first;

delete [] first;

❖ Problem: If the program later tries to access the memory pointed to by


second, either the program will access the wrong memory or it will terminate
in an error

47
Deep Copy
❖ Deep copy: two or more pointers have their own data
second = new int[10]

for (int i = 0; i < 10; ++i)


second[i] = first[i]

48
Assignment Operator
❖ Automatically provided by compiler
❖ Copies value in member variables from one object to the other
❖ If the member variable is a pointer, this copying would lead to Shallow Copy

class Array;
Array arr1;
Array arr2;
arr2 = arr1; // Assignment Operator

49
Overloading Assignment Operator
❖ To help Assignment Operator results in both objects have their own data
(Deep Copy)
❖ Example Code

50
Copy Constructor
❖ When declaring a object, you can initialize it by using the value of an existing
object of the same type Array array(otherArray);
❖ Automatically provided by compiler: element-wise initialization
❖ Like Assignment Operator, if the member variable is a pointer, this
initialization would lead to Shallow Copy

51
Class & Cause to Shallow Copy
❖ If a class has pointer member variables:
❖ During object declaration, the initialization of one object using the value of
another object would lead to a shallow copying of the data if the default
member-wise copying of data is allowed.
❖ If, as a parameter, an object is passed by value and the default member-
wise copying of data is allowed, it would lead to a shallow copying of the
data.
void display(Array array);

52
Copy Constructor Called
❖ The copy constructor automatically executes in three situations
❖ When an object is declared and initialized by using the value of another
object
❖ When, as a parameter, an object is passed by value
❖ When the return value of a function is an object

53
Overloading Copy Constructor
❖ To help Copy Constructor results in both objects have their own data (Deep
Copy)
❖ Example Code:

54
Summarise

55

You might also like