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

Lecture 3 DS

The document provides an introduction to data structures and algorithms, focusing on concepts like pointers, references, shallow and deep copies, and inheritance. It covers function parameter passing methods, polymorphism, operator overloading, and the use of friend functions in classes. Additionally, it discusses the rules and examples for implementing these concepts in C++.

Uploaded by

Sondos Belal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture 3 DS

The document provides an introduction to data structures and algorithms, focusing on concepts like pointers, references, shallow and deep copies, and inheritance. It covers function parameter passing methods, polymorphism, operator overloading, and the use of friend functions in classes. Additionally, it discusses the rules and examples for implementing these concepts in C++.

Uploaded by

Sondos Belal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Introduction to Data Structures

and Algorithm
21COMP04C
2023

Lecture3
1
Lab2 submission
• Labs are ungraded
• Lab 2 submission is next Sunday (

2
References
• The “pointer” and “reference” both are used to point or refer an
another variable
pointers reference
int a = 5,b=6; int a = 5,b=6; A reference must be initialized
int *p = &a; int &ref = a; when it is declared.
int *p = &a; int &ref = a; reference can’t be reassigned
p=&b &ref = b; //invalid
A pointer can be assigned to a References cannot be NULL NULL
NULL value.
int a = 5; int a=5; Reference are easy to use
int *p = &a; int &ref = a;
*p=6 ref=6;
cout<<a; //print 6 cout<<a //print 6

Use -> opertor use . operator To access member of object of


class
3
Shallow Vs. Deep Copy and Pointers
1-Shallow copy (want to copy array then delete original)
• int *first= new int[10]
• int *second;

• second = first; Copy statement


Changing any element in second will change the same element in first

• delete [] first;

4
2-Deep copy
• Two or more pointers have their own data
• Manually create a new array and copy all elements
int *first= new int[10]
………..
int *second;
//Deep copy operation
second = new int[10];
for (int i=0;i<10;i++)
{
second[i]=first[i] FIGURE 3-19 first and second both pointing to their own data
}

delete [] first;

5
Lecture 3
Inheritance
Polymorphism

Lecture Resources
Data-Structure Using C++ by D.S. Malik (ch 1)
Data Structures Using C by Reema Thareja (ch2)
These slides are adapted for the text book's slides 6
Passing parameters of a functions by value (Copy)
int sum_and_inc (int x, int y)
{
x++; y++; return x+y;
}
Values of a and b and
void main()
{
copied to x and y , the
int a=3, b= 3,c; same can happened to class
c=sum_and_inc(a,b) object
cout<< a<<b<<c<<endl
}
Output
338
Passing parameters to a function by pointers
int sum_and_inc (int *x, int *y)
{
(*x)++; (*y)++; return *x+*y;
}
int main()
{
int a=3, b= 3,c;
c=sum_and_inc(&a,&b);
cout<< a<<b<<c<<endl
}
Output
448
Passing parameters to a function by pointers
int sum_and_inc (int &x, int &y)
{
x++; y++; return x+y;
} Also use reference when passing
void main() objects because copying objects is
{ expensive
int a=3, b= 3,c;
c=sum_and_inc(a,b); The general rule would be:
cout<< a<<b<<c<<endl If you are just going to read the object, pass a const reference
If you are going to modify the object, pass a reference (or pointer).
} If you are definitely going to make a copy of the object, pass it by
value.
Output
448 void func ( const clocktye &myclock)
Inheritance
• Inheritance lets us create new classes from existing classes.
• The existing classes are called the base classes;
• The new class that we create from the existing classes is called the
derived class.
• The derived class inherits the properties of the base classes
• Inheritance can reduce software complexity.
Example

Person

Full time Part time


Types of Inheritance
• Single
• derived class has only one base class
• Multiple

Source:://patilinfotech.wordpress.com/2018/03/09/inheritance/
Defined single inheritance Shape
base

Circle
Derived

assume class shape is already created

Example:
Public single inheritance

Private single inheritance


Facts about the base and the derived classes
should be kept in mind
1. The private members of a base class are private to the base
class(hidden from the derived class);
• when you write the definitions of the member functions of the derived class,
you cannot directly access the private members of the base class.
2. The public members of a base class can be inherited either as public
members or as private members by the derived class.
• the public members of the base class can become either public or private
members of the derived class. (based on access specifier of inheritance)
3. The derived class can include additional members—data and/or
functions.
Facts about the base and the derived classes
should be kept in mind
4. The derived class can redefine the public member functions of the
base class. (overriding)
• in the derived class, you can have a member function with the same
name, number, and types of parameters as a function in the base
class.
5. All member variables of the base class are also member variables of
the derived class. Similarly, the member functions of the base class
(unless redefined) are also member functions of the derived class.
(Remember Rule 1 when accessing a member of the base class in the
derived class.)
class boxType: public rectangleType
Example {
public: overloading
class rectangleType void setDimension(double l, double w, double h);
{
• cs
public:
double getHeight() const;
double area() const; overriding
void setDimension(double l, double w); double volume() const;
double getLength() const; void print() const; overriding
double getWidth() const; boxType();
double area() const; boxType(double l, double w, double h);
double perimeter() const; private:
void print() const; double height; };
rectangleType();
rectangleType(double l, double w); void main() {
private: rectangleType myRectangle(5.0, 3.0); //Line 1
double length; boxType myBox(6.0, 5.0, 4.0);
double width; }; cout<< myRectangle.area() //15
cout<< myBox.area() //120
cout<< myBox.getLength() //6
myBox.setDimension(11,12,13) // set D of box
myBox.setDimension(11,12) // set D of Rec}
(Overriding) Functions of the Base Class (not overloading)
class rectangleType class boxType: public rectangleType
{ {
• cs
public: public: overloading
void setDimension(double l, double w); void setDimension(double l, double w, double h);
double getLength() const; double getHeight() const;
double getWidth() const; double area() const; overriding
double area() const; double volume() const;
double perimeter() const; void print() const; overriding
void print() const; boxType();
rectangleType(); boxType(double l, double w, double h);
rectangleType(double l, double w); private:
private: double height; };
double length;
double width; }; double boxType::area() const
{
void boxType::print() const return 2 * (getLength() * getWidth()
{ rectangleType::print(); + getLength() * height
cout << "; Height = " << height; } + getWidth() * height); }
class rectangleType class boxType: public rectangleType {
{ public:
void setDimension(double l, double w, double h);
public: double getHeight() const;
void setDimension(double l, double w); double area() const;
double getLength() const; double volume() const;
double getWidth() const; void print() const;
double area() const; boxType();
boxType(double l, double w, double h);
double perimeter() const; private:
void print() const; double height; };
rectangleType();
rectangleType(double l, double w); void boxType::setDimension(double l, double w,
private: double h)
double length; { rectangleType::setDimension(l, w);
double width; }; If (h >= 0)
height = h;
else
height = 0; }
Constructors of Derived and Base Classes
• constructors of a derived class can (directly) initialize only the (public
data) members inherited from the base class of the derived class.
• Because constructors cannot be called like other functions, the
execution of a derived class constructor must trigger the execution of
one of the base class constructors.
boxType::boxType(double l, double w, double h) : rectangleType(l, w)
{
if (h >= 0)
height = h;
else
height = 0;
}
Another Example page 73
Protected Members of a Class
• the derived class cannot access private members of a class.
• However, it is sometimes necessary for a derived class to access a
private member of a base class.
• If you make a private member become public, anyone can access that
member.
• for a base class to give access to a member to its derived class and
still prevent its direct access outside the class, you must declare that
member under the member access specifier protected.
• A derived class can directly access the protected member of a base
class.
Inheritance as public, protected, or private
Protected inheritance
Private Inheritance
Member access specifier and Inheritance as
public, protected, or private

Source: https://www.bogotobogo.com/cplusplus/private_inheritance.php
Friend Functions of Classes
• A friend function of a class is a nonmember function of the class, but
has access to all the members (public or non-public) of the class
class class_friend
{
friend void Func(parameter 1, parameter2,…….
.
. Where to put friend
}; No friend in definition

void Func(/*parameters*/)
{ ….. }
void friendFunc(Friendclass &Object1) class Friendclass
{ {
Object1.x = 88;//Error if not friend friend void friendFunc(Friendclass object1);
Object1.print(); public:
// local variable void print();
Friendclass Object2; void setx(int a);
Object2.x = 45; private:
Object2.print(); } int x; };

void main{ void Friendclass ::print()


Friendclass Object3; {
Object3.setx(32); cout << "In friendclass : x = " << x <<endl;
Object3 .print(); }
friendFunc(Object3); void Friendclass ::setx(int a){
Object3 .print(); x = a; }
}
Try the program without reference in the
friend function
Polymorphism
Lecture Resources
Data-Structure Using C++ by D.S. Malik (ch 1 & 2)
Data Structures Using C by Reema Thareja (ch2)

These slides are adapted for the text book's slides


Polymorphism:
Operator and Function
Overloading
Operator overloading
Operators in C++
• term operator overloading refers to giving the normal C++ operators,
such as +, *, <=, and +=, additional meanings when they are applied
to user-defined data types.
• Take a = b + c as example; works only with basic types such as int and
float, and attempting to apply it when a, b, and c are objects of a
user-defined class will cause complaints from the compiler. However,
using overloading, you can make this statement legal even when a, b,
and c are user-defined types.
Overloadable operators

The operators
. .* :: ?: sizeof //may not be overloaded.
All other operators may be overloaded, i.e.
+ - * / = < > += -= *= /= << >> <<= >>= == != <= >= ++ -- % & ^ ! | ~ &= ^= |=
&& || %= [] () , ->* -> new delete.

• The order of precedence cannot be changed for overloaded operators.


• Default arguments may not be used with overloaded operators
• New operators cannot be created
• Overloading must be explicit, i.e. overloading + does not imply += is
overloaded
Example: myClock.printTime();
myClock.incrementSeconds();
class clockType if (myClock.equalTime(yourClock))
{ {
private: }
int hr;
int min;
int sec; // how can I make my program do that
clockType myclock,Clock1,Clock2
public: cout << myClock; //insertion operator <<
void setTime(int hours, int minutes, int seconds);
myClock++; //increment operator ++
void printTime() const;
void incrementSeconds(); Clock3=Clock1+Clock2 // addition operator
void incrementMinutes(); if (myClock == yourClock) //relational operators
void incrementHours(); .
bool equalTime(const clockType otherClock) const; Note:
. The only built-in operations on classes are :
clockType(int hours, int minutes, int seconds); 1. assignment operator = ( clock1=clock2)
.
clockType(); 2. member selection operator . (clock1.hr)
};
Operator functions
• Operator functions can be
• Member Functions
• Nonmember Functions (friend to class)

Return_type operator operator_symbol (arguments)


{…………..}
Rules for defining operator overloading
function
• The function that overloads any of the operators (), [], ->, or = for a
class must be declared as a member of the class.
• Suppose that an operator op is overloaded for a class—say, Classx
• If the leftmost operand of op is an object of a different type (that is, not of
type Classx), the function that overloads the operator op for Classx must be a
nonmember—that is, a friend of the class Classx.
• This is why when overload the insertion operator, <<, or the extraction
operator, >>, for a class , the operator function must be nonmembers—that
is, they must be a friend functions of the class
How to overload binary operator (+, *, ==, and !=….) as non member function
class rectangleType
{
bool operator==(const rectangleType& rectangle1 ,
friend bool operator ==(const rectangleType&, cosnt const rectangleType& rectangle2)
rectangleType&); {
public: return (rectangle1.length == rectangle2.length
void setDimension(double l, double w); && rectangle1.width == rectangle2.width);
double getLength() const; }
double getWidth() const;
void main()
double area() const;
{
double perimeter() const;
rectangleType rec1(3,6),rec2(5,6);
void print() const; if (rec1==rec2):
rectangleType(); cout<<“true in the first try”;
rectangleType(double l, double w); rec2.setDimension(3,6);
private: if (rec1==rec2):
double length; cout<<“true in the second try”;}
double width;};
Overload the + operator to add len and width of the two rectangles and return a new rectangle??
Friend rectangleType operator+(const rectangleType&, const rectangleType&)
How to overload binary operator (+, *, ==, and !=….) as a member function
class rectangleType bool rectangleType::operator==
{ (const rectangleType& rectangle) const
public: {
void setDimension(double l, double w); return (length == rectangle.length &&
double getLength() const; width == rectangle.width);
}
double getWidth() const;
double area() const;
double perimeter() const; void main()
void print() const; {
rectangleType operator+(const rectangleType&) const; rectangleType rec1(3,6),rec2(5,6);
rectangleType operator*(const rectangleType&) const; if (rec1==rec2)
bool operator==(const rectangleType&) const; cout<<“true in the first try”;
rec2.setDimension(3,6);
bool operator!=(const rectangleType&) const;
if (rec1==rec2)
rectangleType();
cout<<“true in the second try”;}
rectangleType(double l, double w);
private: rec1==rec2
double length; This line is converted by the compiler to
double width;}; rec1.operator==(rec2)
Overloading the Stream Insertion (<<) and
Extraction (>>) Operators
• What do we want
• rectangleType myRectangle(3,6);
• cout << myRectangle
• cin >> myRectangle
• << and >> operator function must be nonmembers (friend class) why?
• cout is an object of ostream class
• cin is an object of isteram class
How to overload binary operator (>> and <<) as non member function
class rectangleType ostream& operator<< (ostream& osObject, const
{ rectangleType& rectangle)
friend ostream& operator<< (ostream&, const rectangleType &); {
friend istream& operator>> (istream&, rectangleType &); osObject << "Length = " << rectangle.length << ";
Width = " << rectangle.width;
public:
return osObject; }
void setDimension(double l, double w);
double getLength() const; istream& operator>> (istream& isObject,
double getWidth() const; rectangleType& rectangle)
double area() const; {
double perimeter() const; isObject >> rectangle.length >> rectangle.width;
void print() const; return isObject; }
rectangleType();
rectangleType(double l, double w);
private: void main()
double length; {
double width;}; rectangleType rec1(3,6),rec2;
cout<<rec1;
cin>>rec2;
cout<<rec1<<rec2;}
OVERLOADING UNARY OPERATORS
• ++ , -- , - , + , *, ~ , !
• similar to the binary operators. The only difference is that in the case
of unary operators, the operator has only one argument
• If the operator function is a member of the class, it has no
parameters.
• If the operator function is a nonmember—that is, a friend function of
the class—it has one parameter.
The Pointer this
• A member function of a class Class test
can (directly) access the data {
members of that class for a …………
given object. Sometimes it is
necessary for a function test test::funcOne()
member to refer to the object { ...
as a whole, rather than the return *this;
object’s individual data }
members };
• Every object of a class
maintains a (hidden) pointer to Void main()
itself, and the name of this {
pointer is this. test x,y;
• In C++, this is a reserved word. y = x.funcOne();
• The pointer this is available for }
you to use

You might also like