OOP SecAmerged
OOP SecAmerged
namespace first_space{
void printf(char *p){
cout << "Inside first_space" << endl; }
}
int main(){
printf("hello world");
first_space::printf("hello world");
}
Why Using ‘namespace std’?
#include<iostream> What will be the output?
using namespace std;
namespace first_space{
void printf(char *p){
cout << "Inside first_space" << endl; }
}
int main(){
printf("hello
world\n");
first_space::printf("hello world");
What will be the output???
What is a namespace?
• Additional information to differentiate similar functions, classes, variables etc.
with the same name, available in different libraries.
• Namespace, defines a scope. To call namespace-enabled version of either
function or variable, prepend the namespace name to the function / variable :
std::cout <<
“hello”<<std::endl;
std::cin.get();
• This can be avoided with preprocessor directives :
using namespace std; // std is abbreviation of namespace standard
cout <<“hello”<<endl;
•3 types of namespace-
•Standard namespace
Using user defined namespace
#include <iostream>
using namespace std;
namespace first_space{
What will be the output?
void display(){
cout << "Inside first_space" << endl; }
}
namespace second_space{
void display(){
cout << "Inside second_space" << endl; }
}
int main () {
// Call function from first name space.
first_space::display();
// Call function from second name space.
second_space::display();
}
Using user defined namespace
#include <iostream>
using namespace std;
namespace first_space{
What will be the output?
void display(){
cout << "Inside first_space" << endl; }
}
namespace second_space{ Inside first space
void display(){ Inside second space
cout << "Inside second_space" << endl; }
}
int main () {
// Call function from first name space.
first_space::display();
// Call function from second name space.
second_space::display();
}
Using user defined namespace (Example)
#include <iostream>
using namespace std;
namespace MyNameSpace {
int i, k;
void myfunc (int j)
{ cout << j; }
class myclass {
public:
void seti (int x) { i = x; }
int geti () { return i; }
};
}
Using user defined namespace (Example)
using MyNameSpace::k;
k = 10;
namespace Demo {
int a;
}
int x;
namespace Demo {
int b; }
int main() {
using namespace Demo;
a = b = x = 100;
cout << a << " " << b << " " << X;
return 0;
}
Using user defined namespace (Example)
#include <iostream>
using namespace std;
namespace Demo {
int a; // In Demo namespace // Namespaces are additive
}
int x; // this is in global namespace
namespace Demo {
int b; // this is in Demo namespace, too}
int main() {
using namespace Demo;
a = b = x = 100;
cout << a << " " << b << " " << x;
return 0;
}
Using user defined namespace (Example)
// use explicit std:: qualification.
#include <iostream>
int main() {
double val;
std::cout << "Enter a number: ";
std::cin >> val;
std::cout << "This is your number: ";
std::cout <<<< val;
return 0;
}
Using user defined namespace
1. Define two namespaces “SquareSpace” and “CircleSpace”
both containing a function with same name “Area”. Use necessary
variables.
2. Take input of a variable a. Call both functions from main program and
show the output. Provide the input as parameter.
3. The “Area()” function in the SquareSpace should return the area of a
square considering the parameter.
4. The “Area()” function in the CircleSpace should return the area of a
circle considering the parameter.
Starting with Classes
Structure in C
What will be the output?
Structure in C
What will be the output?
Structure in C
What will happen now?
What will be the output?
Structure in C
What will happen now?
What will be the output?
int myclass::get_a()
{return a;}
Class(Example)
#include <iostream>
using namespace std;
int main()
class myclass { {
// private to myclass myclass obl, ob2;
int a; obl.a=10;
public: ob2.a=99;
void set_a(int num); cout << ob1.get_a() << "\n";
int get_a(); cout << ob2.get_a() << "\n";
}; return 0;
}
void myclass::set_a (int num)
{ a = num;}
What will be the output?
int myclass::get_a()
{return a;}
Class(Example)
#include <iostream>
using namespace std;
int main()
class myclass { {
// private to myclass myclass obl, ob2;
int a; obl.a=10; //cannot acess private member
public: ob2.a=99;
void set_a(int num); cout << ob1.get_a() << "\n";
int get_a(); cout << ob2.get_a() << "\n";
}; return 0;
}
void myclass::set_a (int num)
{ a = num;}
//Error!
int myclass::get_a()
{return a;}
Abstraction
▪ Abstraction means, showcasing only the required things to the outside world
while hiding the details
▪ Continuing our example, Human can talk, walk, hear, eat, but the details are
hidden from the outside world.
▪ Difference between abstraction and encapsulation
▪ The most important difference between Abstraction and Encapsulation is that
Abstraction solves the problem at design level while Encapsulation solves it at
implementation level.
▪ Abstraction is used for hiding the unwanted data and showing the related data.
Encapsulation hides the data and code into a single unit to protect the data
from outside
Inheritance
▪ Considering Birds a class, which has properties like claws, feathers, eyes etc,
and functions like laying eggs, eat, see etc.
▪ Chicken and Ostriches are also classes, but most of the properties and
functions are included in Birds, hence they can inherit everything from class
Birds using the concept of Inheritance.
Inheritance
Birds Class
Claws
Feathers
Lays eggs()
Eats()
See()
Birds Birds
Class Class
canFly() canWalk()
Inheritance(EXAMPLE)
#include <iostream>
int main() {
using namespace std;
derived ob;
ob.setx(10); // access member of base class
class base {
ob.sety (20); // access member of derived class
int x;
ob.showx(); // access member of base class
public:
ob.showy(); // access member of derived class
void setx (int n) { x = n; }
return 0;
void showx() { cout << x <<< '\n'; }
}
};
Member function
definition outside the class
Function Definition – inside class
declaration
Another method of defining
member function is to replace
the function declaration by the
actual function definition inside
the class.
Objects
● Objects are the basic run-time entities in an object oriented system.
● Objects take up space in the memory and have an associated address like
structure in C.
● Each object has its own copy of the class member vars. But there will only be
one definition for member function in memory, which is shared by all objects
of the class.
● Messaging : When a program is executed the objects interact by sending
messages to one another.
Objects
s2
ID: void
showCGPA(){
cgpa: cout<<“CGPA
is:”<<cgpa;
}
Operations in class
● Assigning objects
● Passing object to function
● Returning object from function
● Array of objects
● Create pointer/ reference of objects
Assigning Objects
● One object can be assigned to another if both objects are of the same type
(both are objects of the same class)
● When one object assigned to another, bitwise copy of all the members is
made.
Assigning Objects Example
Syntax
void func(student ob){
// function body
}
int main(){
Student ob;
func(ob);
}
Passing Objects to a function Example
● Design a Point class which will contain the variables X, Y(private)
● Create a function “SetXY(int a, int b)” to set the value of X and Y.
● Create an object p1 of the class. Set the values.
● Create a function “Distance (Point p2)” which will calculate and show the
distance between two points p1 and p2.
● Formula to calculate distance: d =
● Include the “math.h” to use sqrt() function
Passing Objects to a function Example
Returning Objects from a function
Syntex
student func(){
student ob1;
return ob1;
}
int main(){
Student ob2;
ob2 = func();
}
Returning Objects from a function Example
● Arrays of objects are accessed in the same way as accessing arrays of other
types of variables
Syntax
Declaration:
Class_name object_name[size];
Accessing:
object_name[index].member_variable;
object_name[index].member_function();
Rewrite this Code declaring array of objects
Using pointer to objects
originalVariable = 20;
std::cout << referenceVariable;
referenceVariable = 30;
std::cout << originalVariable;
Example of Reference
// Both the original variable and the reference point to the same data
originalVariable = 20; // Change through the original variable
std::cout << referenceVariable; // Outputs: 20
Derived Class
Inheritance
Inheritance
Private member
Student Class
Student
int theory;
int sessional;
void setMarks(...);
int getTheory();
int getSessional();
Inheritance
Student
As we know, each student at every
int theory;
level has both theoretical and int sessional;
sessional courses. However, at
level 4, there is an additional
void setMarks(_);
course called 'thesis.' Therefore, int getTheory();
we need to design a class int getSessional();
specifically for Level 4 students.
L4Student
Extending Student Class
Private member
Student L4Student
int theory; ...
int sessional; int thesis;
void setMarks(...); ...
int getTheory(); void setThesis(...);
int getSessional(); int getThesis();
Extending Student Class
Private member
L4Student
...
int thesis;
...
void setThesis(...);
int getThesis();
L4 students also have theoretical and sessional courses. Therefore, in the L4Student class, we also need
to implement functionalities for setting theory and sessional marks. We already have a class called
'Student' that includes these functionalities, so we can inherit from that class.
Extending Student Class
Student
int theory;
int sessional;
void setMarks(_);
int getTheory();
int getSessional();
L4Student
Extending Student Class
Student
int theory;
int sessional;
void setMarks(_);
int getTheory();
int getSessional();
L4Student
Student
int theory; int
sessional;
void setMarks(_); int
getTheory(); int
getSessional();
Extending Student Class
Student L4Student
int theory; int int thesis;
sessional;
Student
void setMarks(_); int
getTheory(); int void setMarks(_);
getSessional(); int getTheory();
int getSessional();
void setThesis(...);
int getThesis();
Extending Student Class
Student L4Student
int theory; int thesis;
int sessional; Student
void setMarks(_);
void setMarks(_);
int getTheory(); int getTheory();
int getSessional(); int getSessional();
void setThesis(...);
int getThesis();
Access Specifier Summary
ERROR
Dept is private in class
teacher. Can not be
accessed from nonmember
of the class
Solution???
Solution 1
Solution 2 using Friend Function
Solution 3 using Friend Function
Inline Function
How function call works
▪Argument of thefunction is int odd(int x)
stored in stack {
▪Control transferred to thefunc return x%2;
being called. }
▪CPU then executes thefunctions int main()
code
{ int result;
▪Stores thereturn value in a
predefined memory register
for(int i=0; i<=10000;
▪Control is returned to the calling i++){ result = odd(i)
function ; if(result==1)
▪overhead of the function call cout <<i<< “ is odd”;
increases if the function is called a lot }
of time }
Solution?
Inline Function - Inline function is Inline function syntax
a function that is expanded in
line when it is called. inline return_type
function_name(parameters)
▪When the inline function is
{
called, whole code of the inline // function code
function gets inserted or }
substituted at the point of inline
function call.
▪This substitution is performed by
the C++ compiler at compile
time.
Inline Function
inline int odd(int x)
{
return x%2;
} Function statement is copied by
the compiler
int main()
{ int result;
for(int i=0; i<=10000;
i++){ result = odd(i)
; if(result==1)
cout <<i<< “ is
odd”;
} }
Inline Function
inline int add(int a, int b) {
return a + b;
}
int main() {
int x = 10;
int y = 20;
int z = add(x, y); // Instead of a function call, the code 'x + y' is inserted here
return z;
}
Inline Function
int main() {
int x = 10;
int y = 20;
int z = x+y// Instead of a function call, the code 'x + y' is inserted here
return z;
}
Advantages
▪ Function call overhead doesn’t occur. Much faster than normal functions when
it is small
▪ It also saves the overhead of push/pop variables on the stack when function is
called.
▪ It also saves overhead of a return call from a function.
▪ Once inlining is done, compiler can perform intra-procedural
optimization if specified.
▪ Inline function may be useful (if it is small) for embedded systems because inline
can yield less code than the function call preamble and return.
Disadvantages
▪ If Inline functions are too large and called too often, program grows
larger.
▪If too many inline functions are used, codes become larger.
Therefore only short functions are declared as inline functions.
Restrictions
▪ An inline function must be defined before it is first called.
▪ Inline specifier is a request, not a command.
▪ If, for various reasons, the compiler is unable to fulfill the request, the
function is compiled as a normal function and the inline request is
ignored.
▪ Some more restrictions: functions should not consists of
▪ Static variable
▪ A loop statement
▪ A switch or a goto statement
Example 1-Inlining Member Function
class samp inline int samp::divisible(){
{ int i, j; return !(i%j);
public:
void initialValue (int a, }
int b); int main()
int divisible(); {
}; samp ob1, ob2;
void samp:: initialValue (int a, ob1. initialValue (10, 2);
int b) ob2. initialValue (10, 3);
{ if(ob1.divisible())
i = a; cout<<“10 is divisible by 2”;
j = b;
}
Example 2
inline int min (int a, int b) int main()
{ {
return a<b ? a : b; cout << min (-10, 10);
}
inline long min (long a, long b) cout << min (-10.01, 100.002);
{ cout << min (-10L, 12L);
return a<b ? a : b;
} return 0;
inline double min (double a, double b) }
{
return a<b ? a : b;
}
Automatic Inline Function
Automatic In-Lining
▪If a member function’s definition is short enough, the
definition can be included inside the class declaration. It
causes the function to automatically become an in-line
function.
OUTPUT
7
Garbage value
Example 2
Example 2
OUTPUT
7
7
Example 3
Example 3
OUTPUT
7 16
7 Garbage value
Example 4
Example 4
OUTPUT
7 10
7 16
Example 6
Compilation error
int myclass::x is private
Example 5
Example 5
Initializing static variable within
class is not allowed
OUTPUT
Value of n: 15
It is possible to use a static
variable/function or global variable/
Value of n: 10
function inside a static function
Example 3
OUTPUT
Value of n: 15
What will happen if non static member
variable is accessed inside static function??
Value of n: 10
Static Member Function
▪ A static member function can access only other static members of its class.
▪ It can access non-static global data and functions
▪ Static member function does not have a “this” pointer
▪ Virtual static member functions are not allowed - inheritance
▪ A static member function can be invoked by an object of its class, or it can
be called independent of any object. Via the class name and the scope
resolution operator.
Assignment
▪ Why is it necessary to use static data members?
▪ Why static member function does not have “this” pointer?
▪ Why non static member variable can not be accessed by a static function?
COURSE CODE: CSE 205
COURSE TITLE: OBJECT ORIENTED PROGRAMMING
Polymorphism
▪ Polymorphism is a means of Polymorphism
giving different meaning to
the same message. The
meanings are dependent on
the type of data being Compile time Run time
processed. polymorphism polymorphism
void main(){
cout << totalMark (80,90);
cout << totalMark (80,90,80);
}
Default Argument
Restriction
int totalMark(int opt = 0, int phy, int chem){
int total = phy+chem+opt;
return total;
}
int totalMark( int phy, int chem, int opt = 0);
int totalMark( int phy, int chem, int opt =0){
int total = phy+chem+opt;
return total;
} totalMark( int phy, int chem, int opt =
int
phy){ int total = phy+chem+opt;
return total;
Default Argument
Restriction
int totalMark(int opt = 0, int phy, int chem){ ERROR
Must be to the right of any parameter
int total = phy+chem+opt;
that don’t have defaults
return total;
}
int totalMark( int phy, int chem, int opt = 0); int
ERROR
totalMark( int phy, int chem, int opt = 0){ Default can’t be specified both in
prototype and definition
int total = phy+chem+opt; return total;
}
int totalMark( int phy, int chem, int opt =
phy){ int total = phy+chem+opt; ERROR
Default arguments must be constant or
return total; global variables
}
COURSE CODE: CSE 205
COURSE TITLE: OBJECT ORIENTED PROGRAMMING
Constructor
▪ A constructor is a special member function which initializes the objects
▪ Has the exact same name as its class
▪ No return type
▪ It has to be public
▪ Invoked implicitly/explicitly every time an instance/object of that
class is created
▪ Can be overloaded
▪ Are called in the order of creation
▪ Involve memory allocation
▪ Once a constructor is defined, the default one stops working
Type of Constructors
▪3 types of constructors
▪ Default / Zero argument – A constructor that accepts no parameter
is called default constructor. Initializes the members of all the
objects to a predefined value.
▪ Parameterized – A constructor that accepts parameters is called
parameterized constructor. Used when it is necessary to initialize
different values to the members of different objects.
▪ Copy Constructor
Default Constructor
class student { class student {
int id; int id;
public: public:
void setValues(){ student() { Constructor
id = 0; id=0;
} }
int getId(){ int getId() {
return id; return id;
} }
}; };
int main(){ int main(){
student st; student st;
st. setValues(); cout<<st.getId();
cout<<st.getId(); }
Destructor
▪ A destructor is a special member function which destroys the objects
▪ Has the exact same name as its class, preceded by the sign ‘~’
▪ No return type
▪ It has to be public
▪ Can not be overloaded
Destructor
▪ When an object is destroyed-
▪ A function ends
▪ Global objects destroyed when the program ends
▪ a delete operator is called
▪ A block containing local variable ends
▪ Are called in the reverse order of creation
▪ Cleans memory or deallocates memory
Why Defining Destructor is Necessary?
▪ If user defined destructor is not written in class, compiler calls the
default destructor. Default destructor deallocates memory unless we
have dynamically allocated memory. When a class contains a pointer
to allocate memory dynamically, we should write a destructor to
release memory before the class instance/object is destroyed.
▪ This has to be done to avoid memory leak.
Constructor and Destructor
class student{ class student{
int id; int id;
Constructor
public: public:
void setValues(){ student() { id=0;
id = 0; }
} ~student() { Destructor
int getId(){ }
return id; int getId() { return id; }
} };
}; int main(){ student st;
int main(){ cout<<st.getId();
student st; }
st. setValues();
cout<<st.getId();
Default/ Zero Argument Constructor
Parameterized
constructor
Parameterized
constructor
Object
declaratio
n
OUTPUT??
Constructor-Destructor Call
Object
declaratio
n
OUTPUT??
Constructing st1
Constructor-Destructor Call
Constructor-Destructor Call
OUTPUT??
Constructor-Destructor Call
OUTPUT??
Constructing st1
1
Constructor-Destructor Call
OUTPUT??
Constructor-Destructor Call
OUTPUT??
Constructing
st1 1
Destructing st1
Constructor-Destructor Call
OUTPUT??
Constructing st1
1
Destructing st1
Finish
Constructor-Destructor Call
st1
member address
*name 3000
0 4000
id 0 001
Constructor-Destructor Call
OUTPUT??
Constructing st1
st = st1(bitwise
copy)
st st1
member address member address
st st1
member address member address
st st1
member address member address
st st1
member address member address
st st1
member address member address
Already
destroyed
Solution??
▪Assignment
▪Find out the solution
Constructor-Destructor Call
Constructor-Destructor Call
Necessity of Constructor Overloading
▪To gain flexibility
▪To support arrays
▪To create copy
constructors
COURSE CODE: CSE 205
COURSE TITLE: OBJECT ORIENTED PROGRAMMING
The Old Problem
OUTPUT??
Constructing
st1
st1
member address
*name 3000
0 4000
id 0 001
The Old Problem
OUTPUT??
Constructing st1
st = st1(bitwise
copy)
st st1
member address member address
st st1
member address member address
st st1
member address member address
st st1
member address member address
st st1
member address member address
Already
destroyed
A New Solution – User Defined Copy Constructor
▪ The default copy constructor makes a bitwise copy.
▪ Copy Constructor invoked in 3 ways –
▪ When an object is used to initialize another in a declaration
statement(
student st2=st1;)
▪ When an object is passed as a parameter to a function
▪ When a temporary object is created for use as a return value by
a function
▪ User defined copy constructor specifies exactly what occurs when a
copy of an object is made
Copy Constructor Syntax
▪Most Common Form –
classname (const classname &obj){
// body
}
Here obj is a reference to an object that is being used to initialize another object.
▪ Copy Constructor of the student
class – student (const student &obj){
id = obj.id;
name = new char[strlen(obj.name)+1];
strcpy(name,obj.name);
}
Copy Constructor
Invocation
Copy
Constructor
Invocation
Copy Constructor Invocation
▪ Student s1 = s2; // y explicitly initializing x
▪ func(s2); // y passed as a parameter
▪ s1 = func(s1); // y receiving a returned object
Copy Constructor Invocation Example
Copy Constructor
Invocation(initialization)
Copy Constructor
Invocation (passing as
parameter)
Copy Constructor
Invocation(return from
function)
Copy Constructor Invocation Example
1 2
1 2
2
1
3
4
1 2
3
4
1 2
3
4
1 2
3
4
1 2
3
4
1 2
3
10 4
1 2
11
3
10 4
1 2 12
11
3
10 4
1 13 2 12
11
3
10 4
https://docs.google.com/document/d/1oz5co1Na__yKHmdMmXfD1-sJYdFewMLvYdspBnmH_JI/edit?
usp=sharing