0% found this document useful (0 votes)
11 views258 pages

OOP SecAmerged

The document provides an overview of Object Oriented Programming (OOP) concepts, highlighting its advantages over procedural programming, such as encapsulation, polymorphism, and inheritance. It contrasts C and C++, detailing differences in syntax and structure, and explains the importance of classes and objects in OOP. Additionally, it covers namespaces, user-defined namespaces, and the principles of abstraction and encapsulation with examples.

Uploaded by

Shahadat Hossain
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)
11 views258 pages

OOP SecAmerged

The document provides an overview of Object Oriented Programming (OOP) concepts, highlighting its advantages over procedural programming, such as encapsulation, polymorphism, and inheritance. It contrasts C and C++, detailing differences in syntax and structure, and explains the importance of classes and objects in OOP. Additionally, it covers namespaces, user-defined namespaces, and the principles of abstraction and encapsulation with examples.

Uploaded by

Shahadat Hossain
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/ 258

COURSE CODE: CSE 205

COURSE TITLE: OBJECT ORIENTED PROGRAMMING


Procedural Programming
How it works Disadvantages
– Large amount of data intricate flow of
– Split a program into tasks : complex
tasks and subtasks – Gives more importance to algorithms &
– Write functions to carry functions than data being used by the
out the tasks functions
– Instruct computer to – Multi-function programs - shared data
execute the functions in a items are placed as global
sequence – Changes in data structure affects
functions and involves re-writing code
Why OOP?

• OOP treats data as a critical element in the


program development.
• Does not allow data to flow freely around the
system.
• Supports class/structure creation
• Makes maintenance of large program easy
• Contains following features
• Encapsulation
• Polymorphism
• Inheritance
What is OOP?

Object Oriented programming is a


programming style which is associated
with the concepts like class,
object, Inheritance, Encapsulation, Abst
raction, Polymorphism.
Features of OOP
• Encapsulation
• Binds together the code and data it manipulates
• Keeps both safe from accidental interference from outside and misuse
• Polymorphism
• Allows one name to be used for more than one related but
technically different purpose
• Type of data used to call the function determines which specific
version
of the function to be executed
• Function overloading and operator overloading are types of
polymorphism
C++ over C
• C++ allows function overloading and operator
overloading which reduces redundancy
• Through inheritance, redundant code can be eliminated and
extend the use of existing classes
• Principle of data hiding(encapsulation) helps to build a secure
program that can not be invaded by code in other parts of
the program
• Object oriented systems can be easily upgraded from small to
large systems
• Software complexity easily managed
Differences between C & C++
• In C if a function accepts no parameters, then void is mentioned in the parameter
list. This is optional in C++
void display (void); // c style
void display () ; // c++
• All funcs must be proto-typed / declared before usage, in C++.
• If a func return type is mentioned it must return a value in C++. In C it is optional.
• In C if return-type of a func is not specified, it is assumed to be int. In C++ it has to
be
explicitly mentioned. No defaults are allowed
• C++ has an additional bool datatype. C doesnot
C++ Program Structure
• Line 1 & 2 :
Preprocessor directives
– Lines beginning with # are
preprocessor commands
– Include the header file for
functions like cin, cout, etc
– Set the default namespace as
standard
• Line 3: Entry point of the
program. Begin execution
here.
CC vvss CC++++ Input Output
#include <iostream> #include <stdio.h>
using namespace std; int main(){
int main(){ Printf(“hello world”);
cout<<“hello world”; }
}
#include <iostream> #include <stdio.h>
using namespace std; int main(){
int main(){ int a;
int a; scanf(“%d”,&a);
cin>>a; }
}
C vs C++ Output Cntd.
C++ C
include<iostream> include<stdio.h>
int main(){ int main(){
int i;
float j; int i;
char c; float j;
cin>> i >> j >> c; char c;
cout<< i <<“ “<<j<<“ “<<c<<endl; scanf(“%d%f%c”,&i,&j,&c);
}
printf(“%d %f %c\n”,i,j,c);
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");
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;

using namespace MyNameSpace;


i = 10;
Using user defined namespace (Example)

using MyNameSpace::k; // only k is made visible


k = 10; // OK because k is visible

using namespace MyNameSpace; // all members are visible


i = 10; // OK because all members of MyNameSpace are visible
Using user defined namespace (Example)
#include <iostream>
using namespace std;

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?

There will be compilation error. In


C, only information can be stored in
structure. Method/function can not
be stored.
Structure in C++
What will happen now?
What will be the output?

In C++, information and


Method/function both can be
stored in structure.
Class vs Structure
▪ Class and structure have identical capabilities
▪ Both can contain information and methods
▪ By default members of class are private and members of structure are
public.
▪ Class provides the feature of inheritance and structure does not.
Class
▪ Class: The building block of C++ that leads to Object Oriented programming is
a Class.
▪ It is a user defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance
of that class.
▪ A class is like a blueprint for an object/instance.
User defined data type: Class
▪ A class is a collection of method and variables. It is a blueprint that defines
the data and behavior of a type.
Birds
▪ Almost all birds have the functionality
▪ Have feather
▪ Sharp claws
▪ Lays eggs
▪ But birds (pigeons) have some distinct functionality which Pigeons Ostriches
other birds (ostriches) does not have
▪ Here we can take Birds as a class. A class is a blueprint for any functional entity
which defines its properties and its functions. Like birds having feather, laying eggs.
Objects
▪ When we say, Birds, Ostriches or Pigeons, we just mean a type/kind
▪ all the ostriches and pigeons are the forms of these classes. They
have a physical existence while a class is just a logical definition. So
all the ostriches and pigeons are the objects/instances.
Class and Object more examples
▪ Assume a Human class. Human can talk, walk, eat, see etc.
▪ Both Male and Female, performs some common functions, but
there are some specifics to both, which is not valid for the
other.
▪ Females can give birth which males can not.
▪ So Human, Male and Female are classes.
▪ I am Mila, and I am an instance or object of Female class as well as
Human class.
Class
struct struct_name{ class class_name{
//all members //private members
}; public:
main(){ //public members
struct struct_name st1,st2; };
}
main(){
class_name
obj1,obj2;
}
Class
User defined
Keyword class class_name class name
{
Access specifier:
Data member; //variables
Member functions(); //functions to access variables
}; Class name ends
with a semicolon
main(){
class_nameobj1,obj2;
}
Class(Example)
#include <iostream>
using namespace std;
int main()
class myclass { {
// private to myclass myclass obl, ob2;
int a; obl.set_a(10);
public: ob2.set_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;}

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()

Pigeon Class Ostrich Class

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

class derived : public base {


int y;
public:
void sety (int n) { y = n; }
void showy() { cout << y << '\n'; }
};
You should also study these
topics…
▪ Differences between C and C++ (teach yourself 1.6)
▪ What is abstraction and what is encapsulation? Explain with
example.(https://www.guru99.com/difference-between-abstraction-and-
encapsulation.html)
COURSE CODE: CSE 205
COURSE TITLE: OBJECT ORIENTED PROGRAMMING
Class
▪ Class: The building block of C++ that leads to Object Oriented programming is a
Class.
▪ It is a user defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class.
▪ A class is like a blueprint for an object/instance.
▪ Specifying a class-
▪ Class Declaration
▪ Class Function Definition – (inside class declaration, outside class declaration)
Class
Declaration
▪ Class declaration starts with the keyword “class”, followed by user-defined class name
▪ Body of the class enclosed within braces and terminated by a semicolon
▪ Class body contains the declaration of variables and functions. These variables and
functions are collectively called class members.(Function declaration is same as the function
prototype)
▪ Variables declared inside the class are known as data members and functions are known as
member functions.
Class Declaration
SyntaxKeyword
class class_name User defined
{ class name
Class definition does not
Access specifier: [we will learn more later] occupy memory
Data member; //variables
Function //functions to access variable
declaration(); Class name ends
}; with a semicolon
main(){
class_nameobj1,obj2; Declaration of objects of a
} class occupies memory
Function Definition – outside class
declaration
Membership identity
label. Return type class_name :: function_name(arguments)
This label tells the
{
compiler, which class
this function belongs Function body
to. }
Example: Function Definition – outside class
declaration
Function should be declared inside
the class to be a member function of
the class

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

● Accessing member vars of objects


○ Using object name and dot operator.
○ Using member functions.
● Objects of similar types can be assigned to one another.
● Assigning one obj to another will copy all the fields.
Let’s write our own ‘student class’

This is called ‘class Creating objects of a class


declaration’. Class means creating a physical
declaration is not a physical entity for that class. So
entity. This is just a logical creating object occupies
representation of a memory
student. So does not
occupy memory
Accessing members of the class
▪Objects : Instances / occurrence of the class
▪Object Declaration Syntax :-
Class name student s1; object name
student s2;
▪Each instance has its own set of class variables
▪Member functions are only maintained as one copy
▪Accessing member variables of objects :-
▪Using object name and dot operator :
s1.ID= 21;
▪Using member functions.
s1.showID();
Memory allocation for class variables
•The member functions are created and Common for all objects
placed in the memory space only once Member function1
when they are defined as a part of class
declaration
•As all the objects of that class use the Member function2
same member function, no separate
space is allocated for func when objects
are created.
Object 1 Object 2 Object 3
•For each object, space for member Member variable 1
Member variable 1 Member variable 1
variables is allocated separately.
•Separate memory locations for the
objects are essential, as the member Member variable 2
Member variable 2 Member variable 2
variables will hold different values for
different objects.
Let’s write our own ‘student class’
s1
void showID(){
ID: cout<<“ID is:”<<ID;
}
cgpa:

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

What will be the output??


Assigning Objects Example

What will be the output??


OUTPUT???
OUTPUT???
class student{ char class teacher{ char int main(){
*name; *name; student ob1;
public: public: teacher ob2;
void setValues(char *n){ void setValues(char *n){ ob1.setValues("mila");
name = n; name = n;
} } Output??
void showValues(){ void showValues(){
cout<<"Name is cout<<"Name is :"<<name;
:"<<name; cout<<endl; cout<<endl;
} }
}; };
Class student{ char class teacher{ char int main(){
*name; *name; student ob1;
public: public: teacher ob2;
void setValues(char *n){ void setValues(char *n){ ob1.setValues("mila");
name = n; name = n;
} }
void showValues(){ void showValues(){
cout<<"Name is cout<<"Name is :"<<name;
:"<<name; cout<<endl; cout<<endl;
} }
}; };
class student{ char class teacher{ char int main(){
*name; *name; student ob1;
public: public: teacher ob2;
void setValues(char *n){ void setValues(char *n){ ob1.setValues("mila");
name = n; name = n;
} } ob2 = ob1;
void showValues(){ void showValues(){ cout<<endl;
cout<<"Name is cout<<"Name is :"<<name; cout<<"after assigning ob1
:"<<name; cout<<endl; cout<<endl; to ob2";
} } cout<<endl;
}; }; ob2.showValues();
}
class student{ char class teacher{ char int main(){ student ob1;
*name; *name; teacher ob2;
public: public: ob1.setValues("mila");
void setValues(char *n){ void setValues(char *n){
name = n; name = n; ob2 = ob1;
} } cout<<endl;
void showValues(){ void showValues(){ cout<<"after assigning ob1
cout<<"Name is cout<<"Name is :"<<name; to ob2";
:"<<name; cout<<endl; cout<<endl;
Error cout<<endl;
} }
Assignment not allowed as ob2.showValues();
}; }; are not of the same
object
class }
Passing Objects to a function
● Objects can be passed to functions as argument in the same way other types of
data are passed.
● Simply declare the functions parameter as a class type
● Use an object of that class as an argument when calling the function
● As with other types of data, by default all objects are passed by value to a
function.
● Means a bitwise copy of the argument is made
● This copy is used by the function.
● Changes to the object inside the function do not affect the calling object.
Passing Objects to a function

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

● Objects can be returned from functions in the same way other


types of data are returned.
● Simplydeclare the function as returning a class type
● Return an object from that type using return statement
● When an object is returned by a func, a temporary object is automatically
created which holds the return value.
● After returning the value, this object is destroyed
Returning Objects from a function

Syntex
student func(){
student ob1;
return ob1;
}
int main(){
Student ob2;
ob2 = func();
}
Returning Objects from 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 a “showXY()” function to show the values of the coordinates
● Create an object p1 of the class. Set the values.
● Create a function “CalcMidPoint(Point p2)” which will calculate and return the
midpoint between two points p1 and p2.
● Formula to calculate midpoint:
● x = (x1+x2)/2 , y = (y1+y2)/2
Returning Objects from a function Example
Array of Objects

● Objects can be arrayed.

● Syntax for declaring an array of objects is exactly same as declaring an array


of other type of variables

● 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

● Objects can be accessed via pointers.

● When a pointer to an object is used, the object’s members are


referenced using the arrow(->) operator instead of the dot(.) operator.

● When an object pointer is incremented , it points to the next object.


When an object pointer is decremented, it points to the previous
object.
Using pointer to objects Example 1
Using pointer to objects Example 1
Using pointer to objects Example 2
Output??
Output of example 2
Solution??
The “this”
Pointer
▪ “this” pointer is a special type of pointer.
Example
▪ Automatically passed to any member function
when it is called. It is a pointer to the object that Ob.f1();
generates the call •Ob is the object that
▪ The this pointer is an implicit parameter to calls the function
all member functions. •The function f1() is
passed a pointer to
▪ Only member functions are passed “this” pointer. “ob”
▪ Friend functions are not passed “this” pointer
Using “this” pointer to objects Example 1
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
Solution of Passing Objects to a function Example
References
•Can be passed to a function
•Can be returned by a function
•Independent reference can be created
What is a
Reference?
▪A reference variable is an another name for an already existing
variable. Once a reference is initialized with a variable, either
the variable name or the reference name may be used to refer
to the variable.
▪To understand, what a reference parameter is and how it works,
let’s first start with a program that uses a pointer as parameter.
Pointer vs
Reference
Example of Reference

int originalVariable = 10;


int& referenceVariable = originalVariable;

originalVariable = 20;
std::cout << referenceVariable;

referenceVariable = 30;
std::cout << originalVariable;
Example of Reference

int originalVariable = 10; // This is the original variable


int& referenceVariable = originalVariable; // This creates a reference to
'originalVariable'

// Both the original variable and the reference point to the same data
originalVariable = 20; // Change through the original variable
std::cout << referenceVariable; // Outputs: 20

referenceVariable = 30; // Change through the reference variable


std::cout << originalVariable; // Outputs: 30
Advantages of using a
Reference?
▪ References don’t need dereferencing operator to access the value.
They can be used like normal variables. ‘&’ operator is needed only
at the time of declaration.
▪ Members of an object reference can be accessed with dot operator
(‘.’), unlike pointers where arrow operator (->) is needed to access
members.
▪ When an object is passed to a func as a reference, no copy is made.
This is one way to eliminate the troubles associated with the copy of
an argument damaging something needed elsewhere in the program
Self Study(Section 4.4, Teach yourself c++)
▪Show general forms for “new” and “delete”.
▪What are someadvantages of using theminstead of
malloc() and free()?
COURSE CODE: CSE 205
COURSE TITLE: OBJECT ORIENTED PROGRAMMING

Presented By: Lec Faria Alam


What Is Inheritance in General?
What Is Inheritance?
What Is Inheritance in OOP?
• Inheritance is the mechanism by which one class can inherit the properties
of another.
• The new class is a specialized version of the existing class
• Two concepts of Inheritance
• derived class (child) - The class that inherits properties from another
class
• base class (parent) - The class whose properties are inherited by a
derived class
Inheritance
Inheritance
Inheritance
Inheritance
Inheritance
Inheritance
Base Class

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

class L4Student : private Student

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

Inheritance Base Class Derived Class


public Private: Private:
Protected: Protected:
Public: Public:
protected Private: Private:
Protected: Protected:
Public: Public:

private Private: Private:


Protected: Protected:
Public: Public:
Types of Inheritance
COURSE CODE: CSE 205
COURSE TITLE: OBJECT ORIENTED PROGRAMMING
Friend Function
Introduction to Friend Function
▪ Can private members of a class be accessed from outside
the class by a non member function of that class?
▪ Consider two classes, “manager” and “scientists”. You need a
function income_tax() to perform some operations on
objects of both the classes. What should you do?
▪ Write income_tax() function in both the classes?
▪ Is it redundant?
▪ Is there any way to optimize the situation?
▪ “Friend Function” is the solution
Friend Function
▪ Friend function is not a member of the void income_tax(){
class //function body
}
▪ It is defined outside of the class
Manager{
▪ A friend function can access the
//private members
private members of the class, it is //public members
made friend to friend void income_tax();
}
▪ A friend function is defined exactly the
same way as other functions Scientist{
//private members
▪ Just the function is declared as friend //public members
friend void income_tax();
inside the class
}
▪ A func can be declared as friends in
any number of classes
Special Characteristics of Friend Functions
▪Is not a member of the class to which
it is made friend with. Hence friend
func is not in the scope of the class.
▪As it is not a member, friend func can
not be called using the object of that
class.
▪Unlike member functions, it can not
access the members directly. Has to
use an object name and the dot
operator to access.
Special Characteristics of Friend Functions
▪Is not a member of the class to which void income_tax(Manager ob){
salary = 1000;
it is made friend with. Hence friend
func is not in the scope of the class. }
▪As it is not a member, friend func can Manager{
private:
not be called using the object of that double salary;
class. friend void income_tax(Manager ob); //Just
▪Unlike member functions, it can not declared as friend
// not member of the class
access the members directly. Has to }
main{
use an object name and the dot Manager ob;
ob.income_tax(ob);
operator to access.
}
Special Characteristics of Friend Functions
▪Is not a member of the class to which void income_tax(Manager ob){
salary = 1000;
it is made friend with. Hence friend }
func is not in the scope of the class.
▪As it is not a member, friend func can Manager{
private:
not be called using the object of that double salary;
class. friend void income_tax(Manager ob); //Just
▪Unlike member functions, it can not declared as friend
// not member of the class
access the members directly. Has to }
main{
use an object name and the dot Manager ob;
ob.income_tax(ob);
operator to access. income_tax(ob);
}
Special Characteristics of Friend Functions
▪Is not a member of the class to which void income_tax(Manager ob){
salary = 1000;
it is made friend with. Hence friend ob.salary = 1000;
func is not in the scope of the class. }
▪As it is not a member, friend func can Manager{
private:
not be called using the object of that double salary;
class. friend void income_tax(Manager ob); //Just
▪Unlike member functions, it can not declared as friend
// not member of the class
access the members directly. Has to }
main{
use an object name and the dot Manager ob;
ob.income_tax(ob);
operator to access. income_tax(ob);
}
Special Characteristics of Friend Functions
▪It can be declared either in the public or in the private part of
the class without affecting its meaning
▪Can be friend of more than one class
▪Does not have “this” pointer
▪Friend function is not inherited.
Friend Function
Example

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.

▪When a function is defined within a class declaration, the


inline keyword is no longer necessary. However, it is not an
error to use it in this situation.
Example 1
class samp void samp:: initialValue (int a, int b)
{ {
i = a;
int i, j;
j = b;
public:
void initialValue (int a, }
int b); int main(){
int divisible() samp ob1;
ob1. initialValue (10, 2);
{
if(ob1.divisible())
return !(i%j);
} cout<<“10 is divisible by 2”;
}; }
Static Class Member
Static Class Member
▪ When a member variable is declared as static, It causes only one copy of
that variable to exist – no matter how many objects of that class are
declared.
▪ All the objects of that class simply shares that variable.
▪ Same static variable will be used by any classes derived from the class that
contains a static variable – related to inheritance
▪ A static member variable exists before any object of that class is created.
▪ A static class member is a global variable that simply has its scope
restricted to the class in which it is declared.
Static Class Member
▪ A static variable can only be declared inside a class. Definition must be
outside the class.
▪ All static member variables are initialized to 0 by default.
▪ However, it is possible to choose an initial value other than 0 for the
static member variable.
▪ A member function of a class can be declared as static
Example 1
Example 1

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

It is possible to use a static variable before


creating any object of the class
Example 5
Example 5

Compilation error
int myclass::x is private
Example 5
Example 5
Initializing static variable within
class is not allowed

Still, you can initialize here.


Static Member Function
Example 1

As static member functions are not


attached to a particular object, they can
be called directly by using the class OUTPUT
name and the scope resolution Value of n: 10
operator. Value of n: 15
Example 2

It is possible to use a static function


before any object instantiation
OUTPUT
Value of n: 15
Value of n: 10
Example 3

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

▪ Polymorphism can be of two


types-
Function Operator Virtual
Overloading Overloading Function
Polymorphism
▪ Polymorphism is a means of giving different meaning to the same message.
The meanings are dependent on the type of data being processed.
▪ Polymorphism can be of two types-
▪ Compile time polymorphism:
▪ Function Overloading: gives the same name different meaning. The name has
several interpretations that depend on function selection.
▪ Operator Overloading: provides different interpretation of C++ operator
depending on type of its argument
▪ Pure/Run time polymorphism: runtime function selection. Related to
inheritance & will be covered in later sessions. Function overriding.
Compile time Overloading
•Function overloading
•Operator overloading(will be covered by
Lec Faria)
Function Overloading
▪ Functions are either -
▪ member functions—defined inside a class
▪ free functions—defined in global scope
▪ In C, every function has a unique name
▪ C++ allows several functions with the same name
Early Binding vs Late Binding
▪“Early binding refers to events that occur at compile
time.”
▪Early binding occurs when all information needed to call a
function is known at compile time.
▪Examples :
function calls ,overloaded function calls, and overloaded
operators.
Early Binding vs Late Binding
▪“Dynamic binding occurs at run-time and is also called
late- binding.”
▪“Late binding refers to function calls that are not resolved until
run time.”
▪Late binding can make for somewhat slower execution times.
▪Example:
virtual functions
Function Overloading
C C++
int abs(int i); int abs(int i);
float fabs(float f); float abs(float f);
long labs(long l); long abs(long l);
void main(){ void main(){
int i=-2; Int i=-2;
float f = - 3.4; float f = - 3.4;
long l = -3400l; long l = -3400l;
Printf(“%d”,abs(i)); cout<<abs(i);
Printf(“%f”,fabs(f)); cout<<abs(f);
cout<<abs(l)
Printf(“%ld”,labs(l));
Overloading mechanism
▪Function are differentiated by their names and argument list
▪For overloading, Argument list must vary in –
▪ Number of arguments
▪ Types of arguments
▪ Only return types can’t be used to differentiate functions
▪ int func(int i, float f ); Cannot be
▪ float func(int i, float f); overloaded
Overloading mechanism
▪Function are differentiated by their names and argument list
▪For overloading, Argument list must vary in –
▪ Number of arguments
▪ Types of arguments
▪ Only return types can’t be used to differentiate functions
▪ int func(int i, float f ); Cannot be
▪ float func(int i, float f); overloaded
Function Overloading

int sum(int a, int b){ void main(){


int result = a+b intsumInt = sum(5,6);
return result; float sumFloat = sum(4.5,6.0);
}
float sum(float a, float b){ cout<<“Summation of the two
float result = a+b integer numbers : ”<<sumInt<<endl;
return result; cout<<“Summation of the two
} float numbers : ”<<sumFloat<<endl;
}
Function Overloading Example

int fun(int a, int b){


return a + b;
}

float fun(int x, int y) {


return x – y;
}
Function Overloading Example

int fun(int a, int b){ int fun(int a, int b){


return a + b; return a + b;
} }

float fun(int x, int y) { float fun(float x, float y) {


return x – y; return x – y;
} }
Overloading Example
int totalMark (int phy, int chem){
int total = phy+chem;
return total;
}
int totalMark(int phy, int chem, int opt){
int total = phy+chem+opt;
return total;
}
void main(){
cout << totalMark (80,90);
cout << totalMark (80,90,80);
Default
Argument
▪Must be to the right of any parameter that don’t have
default value
▪Default can not be specified both in prototype and
definition
▪Default arguments must be constant or global
variables
Default Argument Example
int totalMark(int phy, int chem, int opt = 0){
int total = phy+chem+opt;
return total;
}

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

Constructor with zero


parameter

Object declaration should


match with constructor
Parameterized Constructors
▪ Parameterized Constructor – When a constructor has been
parameterized,passing the initial values as arguments to the
constructor can be done in two ways while declaring the object:
▪ By calling the constructor explicitly – student object = student(2);
▪ By calling the constructor implicitly – student object(2);
▪ When a constructor is parameterized, appropriate arguments should be
sent for the constructor.
Parameterized Constructors

Parameterized
constructor

Object declaration should


match the constructor
Parameterized Constructors
Parameterized Constructors

Parameterized
constructor

Both the declaration is


allowed
Parameterized Constructors
Parameterized
Constructors
What will happen now?
Parameterized
Constructors
What will happen now?
Solution : Multiple Constructor in a Class/
Constructor Overloading
▪Once a constructor is defined, the default one stops working.
▪ While defining constructor, we should take care of the fact that, there must
be a constructor function for each way that an object of a class will be created.
▪ If a program attempts to create an object for which no matching constructor is
found, compile-time error occurs.
▪ In the previous example, there was compilation error, because the declaration
“student st2” did not match any constructor call. The only constructor function in the
class accepts one parameter. But the declaration provides no argument.
▪To avoid the error in the previous example, we could define 2 constructors.
▪ Default constructor – this would match the declaration of student st2
▪ Parameterized constructor – this would match the declaration of student st1(1)
Multiple Constructors
Constructor-Destructor Call

Object
declaratio
n

OUTPUT??
Constructor-Destructor Call

Object
declaratio
n

OUTPUT??
Constructing st1
Constructor-Destructor Call
Constructor-Destructor Call

•This statement is not object declaration.


•This is an assignment stmt student st = st1;
Constructor-Destructor Call

OUTPUT??
Constructor-Destructor Call

OUTPUT??
Constructing st1
1
Constructor-Destructor Call

▪ func() ends here


▪ The object “st” is a local
variable of the function.
▪ So, destructor for object “st” will
be
called

OUTPUT??
Constructor-Destructor Call

▪ func() ends here


▪ The object “st” is a local
variable of the function.
▪ So, destructor for object “st” will
be
called

OUTPUT??
Constructing
st1 1
Destructing st1
Constructor-Destructor Call

OUTPUT??
Constructing st1
1
Destructing st1
Finish
Constructor-Destructor Call

▪ Int main() ends here


▪ The object “st1” is a local
variable of the function.
▪ So, destructor for object
“st1” will be called
Constructor-Destructor Call

▪ Int main() ends here OUTPUT??


▪ The object “st1” is
a local variable of the Constructing st1
function. 1
▪ So, destructor for Destructing st1
object “st1” will be Finish
called Destructing st1
Constructor-Destructor Call
•Names of the objects character
pointer
OUTPUT
•While calling the function func(st1),
value of st1 is stored in st(a bitwise Constructing st1
1
copy made) Destructing st1 Finish
•st.name = st1.name & st.id = st1.id Destructing st1
• Both the objects names are
pointing to the same memory.
st.name & st1.name are pointing to
the same memory location
• When the destructor is called 1st
time, it destroys the memory
containing the name
Constructor-Destructor Call
OUTPUT??
Constructing
st1

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

*name 3000 = *name 3000


id 5000 000 1 id 4000 0 001
Constructor-Destructor Call
OUTPUT??
Constructing st1
1

st st1
member address member address

*name 3000 = *name 3000


id 5000 000 1 id 4000 0 001
Constructor-Destructor Call
OUTPUT??
Constructing st1
1
Destructing st1

st st1
member address member address

*name 3000 = *name 3000 st1


id 5000 0 1 id 4000 0 001
00
Constructor-Destructor Call
OUTPUT??
Constructing st1
1
Destructing st1
Finish

st st1
member address member address

*name 3000 = *name 3000 st1


id 5000 0 1 id 4000 0 001
00
Constructor-Destructor Call
OUTPUT??
Constructing st1
1
Destructing st1
Finish
Destructing st1

st st1
member address member address

*name 3000 = *name 3000 st1


id 5000 0 1 id 4000 0 1
00 00

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

*name 3000 = *name 3000


id 5000 000 1 id 4000 0 001
The Old Problem
OUTPUT??
Constructing
st1 1

st st1
member address member address

*name 3000 = *name 3000


id 5000 000 1 id 4000 0 001
The Old Problem
OUTPUT??
Constructing
st1 1
Destructing st1

st st1
member address member address

*name 3000 = *name 3000 st1


id 5000 0 1 id 4000 0 001
00
The Old Problem
OUTPUT??
Constructing
st1 1
Destructing
st1 Finish

st st1
member address member address

*name 3000 = *name 3000 st1


id 5000 0 1 id 4000 0 001
00
The Old Problem
OUTPUT??
Constructing
st1 1
Destructing
st1 Finish
Destructing
st1

st st1
member address member address

*name 3000 = *name 3000 st1


id 5000 0 1 id 4000 0 1
00 00

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.Constructing: St1 (In main)


Copy Constructor Invocation Example

1 2

1. Constructing: St1 (In main)


2. Constructing: St2 (In main)
Copy Constructor Invocation Example

1 2

1. Constructing: St1(In main)


2. Constructing: St2(In main)
3.Copy Constructor Calling St1
(In main)
Copy Constructor Invocation Example
5

2
1
3
4

1. Constructing: St1(In main)


2. Constructing: St2(In main)
3.Copy Constructor Calling St1
(In main)
4.Copy Constructor Calling St1
(In function parameter)
Copy Constructor Invocation Example
5
6

1 2

3
4

1. Constructing: St1(In main)


2. Constructing: St2(In main)
3.Copy Constructor Calling St1
(In main)
4.Copy Constructor Calling St1
(In function parameter)
6.Constructing:
Copy Constructor Invocation Example
5
6
7

1 2

3
4

1. Constructing: St1(In main)


2. Constructing: St2(In main)
3. Copy Constructor Calling St1
(In main)
4.Copy Constructor Calling St1
(In function parameter)
6. Constructing: temp(In local)
7.Copy Constructor Calling temp(in
local)
Copy Constructor Invocation Example
The copy is done before the 5
called function exits, and copies 6
the-existing local variable into 7
the return value.
The called function has access
1 2
to the memory the return value
will occupy, even though 3
that memory is not "in scope"
4
when the copy is being made,
it's still available.
1. Constructing: St1(In main)
2. Constructing: St2(In main)
3.Copy Constructor Calling St1
(In main)
4.Copy Constructor Calling St1
(In function parameter)
6. Constructing: temp(In local)
7.Copy Constructor Calling temp(in
local)
Copy Constructor Invocation Example
5
6 8
7

1 2

3
4

1. Constructing: St1(In main) 8.Destructing temp(local)


2. Constructing: St2(In main)
3.Copy Constructor Calling St1
(In main)
4.Copy Constructor Calling St1
(In function parameter)
6. Constructing: temp(In local)
7.Copy Constructor Calling
temp(in local)
Copy Constructor Invocation Example
5 9
6 8
7

1 2

3
4

1. Constructing: St1(In main) 8. Destructing temp(local)


2. Constructing: St2(In main) 9. Destructing St1(local)
3. Copy Constructor Calling St1
(In main)
4.Copy Constructor Calling St1
(In function parameter)
6.Constructing: temp(In local)
7.Copy Constructor Calling
temp(in local)
Copy Constructor Invocation Example
5 9
6 8
7

1 2

3
10 4

1. Constructing: St1(In main) 8. Destructing temp(local)


2. Constructing: St2(In main) 9. Destructing St1(local)
3.Copy Constructor Calling St1 10. Destructing
(In main) temp(return value)
4.Copy Constructor Calling St1
(In function parameter)
6.Constructing: temp(In local)
7.Copy Constructor Calling
temp(in local)
Copy Constructor Invocation Example
5 9
6 8
7

1 2
11
3
10 4

1. Constructing: St1(In main) 8. Destructing temp(local)


2. Constructing: St2(In main) 9. Destructing St1(local)
3.Copy Constructor Calling St1 10.Destructing
(In main) temp(return value)
4.Copy Constructor Calling St1 Finish
(In function parameter) 10. Destructing
6.Constructing: temp(In local) temp(main)
7.Copy Constructor Calling
temp(in local)
Copy Constructor Invocation Example
5 9
6 8
7

1 2 12
11
3
10 4

1. Constructing: St1(In main) 8.Destructing temp(local)


2. Constructing: St2(In main) 9.Destructing St1(local)
3.Copy Constructor Calling St1 10. Destructing
(In main) temp(return value)
4.Copy Constructor Calling St1 Finish
(In function parameter) 11. Destructing
6.Constructing: temp(In local) temp(main)
7.Copy Constructor Calling 12. Destructing St2(main)
temp(in local)
Copy Constructor Invocation Example
5 9
6 8
7

1 13 2 12
11
3
10 4

1. Constructing: St1(In main) 8.Destructing temp(local)


2. Constructing: St2(In main) 9.Destructing St1(local)
3. Copy Constructor 10. Destructing
Calling St1 (In main) temp(return value)
4. Copy Constructor Finish
Calling St1 (In function 11 Destructing temp(main)
parameter) 6.Constructing: 12. Destructing St2(main)
temp(In local) 13. Destructing St1(main)
7.Copy Constructor Calling
Link to Code

https://docs.google.com/document/d/1oz5co1Na__yKHmdMmXfD1-sJYdFewMLvYdspBnmH_JI/edit?
usp=sharing

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy