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

04 - Object Oriented Programming II - 21122022

object oriented programming part 4 programming

Uploaded by

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

04 - Object Oriented Programming II - 21122022

object oriented programming part 4 programming

Uploaded by

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

CS32080 – Computer Programming

E19-S3 | Nov2022
Dept. of MechanicalEngineering
Faculty of Engineering | South Eastern University of Sri Lanka

03. Object Oriented Programming - II


(1 hr)
M.N.M. Aashiq
1
Topics
1. Philosophy of object-orientation (2 hrs) 4. Object-oriented application development
1. Abstraction (2h)
2. Encapsulation and information-hiding. 1. Instance creation and scope control.
3. Separation of behaviour and implementation. 2. Data structures and iterable collections.
4. Division of a system into manageable 5. I/O and Database handling (3 hrs)
components
1. Stream based I/O and object serialization
5. Reuse and simple interfaces
2. String and file manipulation
2. Introduction to C++ program constructs (2h) 3. Database Programming
1. C++ programming language and API
6. OO analysis and design using UML.(2 hrs)
2. Variables, Data Types and Controls
1. Drawing UML class, package and component
3. Arrays diagrams.
4. Procedures and Functions 2. User-centred design and use cases
5. Program Control Flow 3. Software behaviour representation with
6. Exception Handling sequence diagrams, state machines, and
activity diagrams.
3. Object-oriented programming (2 hrs)
1. Definition and use of classes 7. Advanced topics. (2hrs)
2. Subclasses, inheritance and class hierarchies. 1. Design patterns
3. Polymorphism 2. Evaluation of designs
3. Domain-specific modelling.
4. Architectural patterns
2
Constructors
• Name is the same as the class name
• No return type (or implicitly returns void)
• Hence, no return statement is allowed inside the constructor's body
• Can only be invoked once to initialize the instance constructed
• Constructors are not inherited

// Constructor has the same name as the class Circle c1(1.2, "blue");
Circle(double r = 1.0, string c = "red") { Circle c2(3.4); // default color
radius = r; Circle c3; // default radius and color. Take note
color = c; that there is no empty bracket ()
}

3
Default Arguments for Functions
/* Test function default arguments (TestFnDefault.cpp) */
#include <iostream>
• specify the default value for the using namespace std;
trailing arguments of a function // Function prototype
(including constructor) in the int sum(int n1, int n2, int n3 = 0, int n4 = 0, int n5 = 0);
function header
int main() {
• The default values shall be cout << sum(1, 1, 1, 1, 1) << endl; // 5
specified in function prototype, cout << sum(1, 1, 1, 1) << endl; // 4
cout << sum(1, 1, 1) << endl; // 3
not in the function cout << sum(1, 1) << endl; // 2
implementation // cout << sum(1) << endl; // error: too few arguments }

int sum(int n1, int n2, int n3, int n4, int n5) {
return n1 + n2 + n3 + n4 + n5;
}

4
#include <iostream> // Main Function
#include <string> int main() {
using namespace std; // Construct a Circle instance
Circle c1(1.2, "blue");
class Circle { cout << "Radius=" << c1.getRadius() << "
private: Area=" << c1.getArea() << " Color=" <<
double radius; // Data member (Variable) c1.getColor() << endl;
string color; // Data member (Variable)
// Construct another Circle instance
public: Circle c2(3.4); // default color
// Constructor with default values for data members cout << "Radius=" << c2.getRadius() << "
Circle(double r = 1.0, string c = "red") { Area=" << c2.getArea()
radius = r; << " Color=" << c2.getColor() << endl;
color = c;
} // Construct a Circle instance using default
no-arg constructor
double getRadius() { //Member function (Getter) Circle c3; // default radius and color
return radius; cout << "Radius=" << c3.getRadius() << "
} Area=" << c3.getArea()
<< " Color=" << c3.getColor() << endl;
string getColor() {// Member function (Getter) return 0;
return color; }
}

double getArea() { // Member function


return radius*radius*3.1416;
}
};
5
"public" vs. "private" Access Control Modifiers
• Access control modifier
• Used to control the visibility of a data member or a member function within a class
• 2 types:
• public: The member (data or function) is accessible and available to all in the system
• private: The member (data or function) is accessible and available within this class only
• Ex: Circle: data member radius is declared private
• radius is accessible inside the Circle class, but NOT outside the class
• cannot use "c1.radius" to refer to c1's radius in main()
• Try "cout << c1.radius;" in main()
• On the other hand, the function getRadius() is declared public in the Circle class.
• UML Notation:
• public members are denoted with a "+",
• private members with a "-" in the class

6
Information Hiding and Encapsulation
• A class encapsulates the static attributes and the dynamic behaviors into a "3-
compartment box”
• Once a class is defined, you can seal up the "box" and put the "box" on the
shelve for others to use and reuse
• Anyone can pick up the "box" and use it in their application
• Data member of a class are typically hidden from the outside world,
with private access control modifier
• Access to the private data members are provided via public assessor functions,
e.g., getRadius() and getColor()
• This follows the principle of information hiding
• objects communicate with each others using well-defined interfaces (public functions)
• Objects are not allowed to know the implementation details of others
• Implementation details are hidden or encapsulated within the class
• Rule of Thumb: Do not make any data member public, unless you have a good
reason.

7
Getters and Setters
• To allow other classes to read the value of a private data member
says xxx, you shall provide a get function (or getter or accessor
function) called getXxx()
• To allow other classes to modify the value of a private data member
says xxx, you shall provide a set function (or setter or mutator
function) called setXxx()

8
Keyword "this"
class Circle {
private:
• You can use keyword "this" to double radius; // Member variable called "radius"
refer to this instance inside a ......
public:
class definition. void setRadius(double radius) { // Function's argument also
called "radius"
• One of the main usage of this->radius = radius; // "this.radius" refers to this instance's
keyword this is to resolve member variable // "radius" resolved to the function's
ambiguity between the names of argument.
}
data member and function ......
parameter. For example, };

• "this" is actually a pointer to this


object

9
Keyword "this” (contd.)
• Alternatively, you could use a prefix (such as m_) or suffix (such as _)
to name the data members to avoid name clashes.
class Circle {
private:
double m_radius; // or radius_
......
public:
void setRadius(double radius) {
m_radius = radius; // or radius_ = radius
}
......
}

10
"const" Member Functions
• A const member function, identified by a const keyword at the end of
the member function's header, cannot modify any data member of
this object.

double getRadius() const { // const member function


radius = 0; // error: assignment of data-member
'Circle::radius' in read-only structure
return radius;
}

11
Convention for Getters/Setters and Constructors
For a bool variable xxx, the getter shall be
class Aaa { named isXxx(), instead of getXxx(), as follows:
private:
// A private variable named xxx of type T private: // Private boolean variable bool xxx;
T xxx; public:
public: // Getter
// Constructor bool isXxx() const { return xxx; }
Aaa(T x) { xxx = x; } // Setter
// OR void setXxx(bool x) { xxx = x; }
Aaa(T xxx) { this->xxx = xxx; } // OR
// OR using member initializer list (to be explained later) void setXxx(bool xxx) { this->xxx = xxx; }
Aaa(T xxx) : xxx(xxx) { }
// A getter for variable xxx of type T receives no argument
and return a value of type T
T getXxx() const { return xxx; }
// A setter for variable xxx of type T receives a parameter of
type T and return void void setXxx(T x) { xxx = x; }
// OR void setXxx(T xxx) { this->xxx = xxx; } }
12
Default Constructor
• a constructor with no parameters, or having default values for all the
parameters
• Ex:
• Circle's constructor can be served as default constructor with all the
parameters default
• If C++, if you did not provide ANY constructor, the compiler
automatically provides a default constructor that does nothing
ClassName::ClassName() { } // Take no argument and do nothing

13
Constructor's Member Initializer List
• Instead of initializing the private data members inside the body of the
constructor, as follows: Circle(double r = 1.0, string c = "red") {
radius = r;
color = c;
}

• We can use an alternate syntax called member initializer list as


follows: Circle(double r = 1.0, string c = "red") : radius(r), color(c) { }

14
Destructor
• A destructor, similar to constructor, is a special function that has the
same name as the classname, with a prefix ~, e.g., ~Circle().
Destructor is called implicitly when an object is destroyed.
• If you do not define a destructor, the compiler provides a default,
which does nothing. class MyClass {
public:
// The default destructor that does nothing
~MyClass() { }
......
}

15
Circle c4(7.8, "blue");
cout << "Radius=" << c4.getRadius() << " Area=" << c4.getArea()
Copy Constructor << " Color=" << c4.getColor() << endl;
// Radius=7.8 Area=191.135 Color=blue

• A copy constructor constructs a // Construct a new object by copying an existing object


// via the so-called default copy constructor
new object by copying an existing Circle c5(c4);
object of the same type. cout << "Radius=" << c5.getRadius() << " Area=" << c5.getArea()
• In other words, a copy << " Color=" << c5.getColor() << endl;
// Radius=7.8 Area=191.135 Color=blue
constructor takes an argument,
which is an object of the same
class.
• If you do not define a copy The copy constructor is particularly important. When an object
constructor, the compiler is passed into a function by value, the copy constructor will be
provides a default which copies used to make a clone copy of the argument.
all the data members of the given
object

16
Separating Header and Implementation
• In a better software engineering practice class file and implementation file
will be kept in two separate files.
• This is known as public interface(header declaration) and implementation
• Interface is defined by the designer, implementation can be supplied by
different vendors with different formats.
• Only the Header files are exposed to the user, implementation can be
provided in an object file “.o”(or in a library)
• Source codes will not be provided to the users.

17
Polymorphism
• Polymorphism means having many forms with same name
• Functions and operators are showing different behaviors in different
situation is referred as polymorphism
• In C++ polymorphism is mainly divided into two types,

1. Compile time polymorphism (Function overloading, Operator overloading)


2. Runtime polymorphism (Function overriding or virtual functions)

18
• Function overloading example
#include <iostream> int main() {
using namespace std;
Category cat1;
class Category
{ cat1.polyFunc(9);
public: cat1.polyFunc(8.432);
// function with 1 int parameter cat1.polyFunc(16,25);
void polyFunc(int x)
{ return 0;
cout << "value of x is " << x << endl; }
}

// function with same name but 1 double parameter


void polyFunc(double x)
{
cout << "value of x is " << x << endl;
}

// function with same name and 2 int parameters


void polyFunc(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};

19
• Operator overloading example
#include<iostream> int main()
using namespace std; {
Complex c1(12, 6), c2(2, 4);
class Complex { Complex c3 = c1 + c2; // An example call to "operator+"
private: c3.print();
int real, imag; }
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << "+" << imag <<"i" <<
endl; }
};

20
• Function overriding example
#include <iostream>
//main function
using namespace std;
int main()
{
class base
base *bptr;
{
derived d;
public:
bptr = &d;
virtual void print ()
{ cout<< "print base class" <<endl; }
//virtual function, binded at runtime (Runtime polymorphism)
void show ()
bptr->print();
{ cout<< "show base class" <<endl; }
};
// Non-virtual function, binded at compile time
bptr->show();
class derived:public base
{
public:
return 0;
void print ()
}
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

21
• Virtual function is a member function in the base class which will be redefined in
the derived class later.
• It will let the compiler to perform dynamic linkage or late binding on the
function.
• It is used when there is a need for single base class pointer to refer all the
derived objects. And the functions from proper derived classes will be invoked
by the base class pointer. Otherwise, base class function will only be executed.
• Virtual function determines which function is to be invoked at the runtime
based on the objects pointed by the base class pointer.

22
References

• https://www3.ntu.edu.sg/home/ehchua/progra
mming/cpp/cp3_OOP.html
• https://www.geeksforgeeks.org/polymorphism-
in-c/

23
Thank you

24

You might also like