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

Introduction To Object Oriented Programming1

Uploaded by

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

Introduction To Object Oriented Programming1

Uploaded by

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

Introduction to Object Oriented Programming

Evolution of languages
Object
Oriented

Procedure
Oriented

Assembly

Machine
Language
Introduction to Object Oriented Programming

Evolution of Programming Techniques

Generic

Object Oriented

Modular

Procedure
Oriented

Unstructured
Programming
Introduction to Object Oriented Programming

Unstructured Programming

Main Program

Data
Introduction to Object Oriented Programming

• Introduction to Procedural Programming


• Modular Programming
• Object Oriented Programming
• Generic Programming
• Limitations of Procedural Programming
• Need of Object Oriented Programming

• Fundamentals of OOP
Introduction to Object Oriented Programming

Procedural Programming

Procedure
Main 1
Program Data
Procedure
2
Introduction to Object Oriented Programming

Modular Programming/ Structured Programming

Main Program

Data
Module2
Module1

Data1 Data2
Data1
Data3 Data2

Procedure1 Procedure2
Procedure1
Introduction to Object Oriented Programming

Object Oriented Programming

Object1 Object2
Data1 Data2

Procedure1 Procedure2

Object3
Data3

Procedure3
Introduction to Object Oriented Programming

Generic Programming

Raising the level of abstraction.

What do we do when we program?


• We write a sequence of statements.

What is the level of abstraction?


• We write at the level of source code. That gets
translated directly into machine code, which is less
abstract.
Introduction to Object Oriented Programming

Generic Programming

Normally, when we write source code, the translation to


machine code is direct.
• int *data;
double sum = 0;
for (int i = 0; i < N; i++) {
sum += data[i];
}

The machine code depends only on the source code as


written.
• What machine code comes out of the source code does not depend
on anything other than the source code as written.
Introduction to Object Oriented Programming

Generic Programming

With generic programming, the level of abstraction is higher.


The source code is just a pattern.
• The actual machine code that comes out depends on how the pattern is
“filled-in”.
• template <typename T>
T sum = 0;
for (int i = 0; i < N; i++) {
sum += data[i];
}
• Without knowing T, no machine code can be generated from the above.
Summary:
• With normal programming, we can know what the assembly code should be
just by looking at the source.
• With generic programming, the code is at a higher level. Need to know other
things, like the type parameters.
Introduction to Object Oriented Programming

Generic Programming

So…
• Generic programming is programming that
focuses on the algorithms and code at a
higher level of abstraction that “normal”
programming.
• It is one way of using features such as
templates, so is in some sense an
application of templates.
Introduction to Object Oriented Programming

Generic Programming

Some definitions found in literature…


• Programming with generic parameters
• Programming by abstracting from concrete types
• Programming with parameterized components
• Programming method based in finding the most
representation of efficient algorithms

First definition most commonly used.

Avoids unnecessary code duplication.


Introduction to Object Oriented Programming

Procedural Programming ….Structure of Procedure oriented programs

Main Program

Data
Function1 Function3
Function2

Function5
Function4

Function6 Function8
Function7
Introduction to Object Oriented Programming

Procedural Programming

Also known as Functional programming

It was Introduced to be reused.

Main purpose was to divide problems into several smaller subproblems.

Each of the subproblems can here be solved independently by its own


function

Forces to refer large blocks of memory , therefore data is corrupted


Introduction to Object Oriented Programming

Procedural Paradigm

Global Global
Data Data

Function1 Function2 Function3


• Data • Data • Data
Introduction to Object Oriented Programming

Procedural Programming

All important data is placed globally , so it is accessed by all


functions

Each function has its own local data.

In large program it becomes difficult to identify what data is


accessed by which function

Global data is not secure


Introduction to Object Oriented Programming

Limitations of Procedural Programming

Emphasis is on Larger and


doing things but complex problem
not data becomes strain

Functions have Programs become


unrestricted access difficult to be
to global data modified

Real world objects


are not modeled
effectively
Introduction to Object Oriented Programming

Need of Object Oriented Programming


Benefits of OOP
• Reusability : Defines one class and ‘n’ objects use
the class.
• Redundancy Eliminated : By Inheritance
• Secure : Due to Data Hiding
• Easily upgradable : Due to Modularity
• Message passing technique for communication
between objects make the interface descriptions
with external system much simpler.
• Software complexity can be easily managed
• Extensible : Due to Polymorphism
Introduction to Object Oriented Programming

Fundamentals of OOP

Objects

Classes
Data Encapsulation

Data Abstraction

Inheritance

Polymorphism
Introduction to Object Oriented Programming

Objects

Data

Member
Function
Member
Function
Introduction to Object Oriented Programming

Objects…..Analogy

Students
Data
Office
Supritendant

Secretary
Introduction to Object Oriented Programming

Objects

Elements
Physical Human Collections
of Data
Objects Entities of data
Computers Stotrage
Constructs

And Many more……..


Introduction to Object Oriented Programming

Objects

Basic Run- time entities

Called as a unit that is a collection of


data and functions

What can be an object??????????????


Object

Operation

Operation Attributes Operation

Operation
Example: StudentObject

Enroll()

st_name
st_id
Performa Displayinfo()
branch
nce()
semester

Result()
Introduction to Object Oriented Programming

Class

• Collection of similar type of


objects

• User defined data type

• Mango , Apple and Orange


are members of class fruit
Introduction to Object Oriented Programming

Class

Object3
Object1 Object2

Class A Class A Class A


Feature
Feature Feature

Features Features Features


Class
• Class is a collection of similar objects.

Class
Introduction to Object Oriented Programming

Encapsulation

Data + Logic

Object
Introduction to Object Oriented Programming

Encapsulation

Enclosing of both variables and functions

Combine the data and the operations

Hide the details from user

Allows modularity

Controlled Access to data


Encapsulation

Class: student

Attributes: st_name, st_id,


branch, semester

Functions: Enroll()
Displayinfo()
Result()
Performance()
Introduction to Object Oriented Programming

Abstraction

Hide the implementation details

Asks you to think what you can do to a collection of data


Independently of how you do it
Introduction to Object Oriented Programming

Inheritance

Shape

Square Circle

Cube Cylinder
Introduction to Object Oriented Programming

Inheritance

Expresses commonality among objects

Allows code reusability

Highlights Generalization/Specialization relationships


Inheritance

Point

Line
Introduction to Object Oriented Programming

Polymorphism

The ability of objects to respond differently to the same


message or function call.

Poly Morphism Polymorphism


(Many) (Forms) (Many Forms)
Polymorphism

+
Introduction to Object Oriented Programming

Dynamic Binding

“ Dynamic Binding is the process of linking of


the code associated with a procedure call at
the run-time”.
Introduction to Object Oriented Programming

Message Passing

“The process of invoking an operation on an


object. In response to a message the
corresponding method is executed in the
object”.
Introduction to Object Oriented Programming

StudentObject Message Passing FacultyObject

StudentObject FacultyObject

MgmtObject Performance
Result
Programming with C++

• Variable Declaration
• Global Scope
• const
• Reference Variables
• Comments
• Function Prototypes

• Inline functions
Programming with C++

• Function Overloading
• Default and Constant arguments

•cout & cin

•Formatting & I/O manipulators

•new and delete operators


Introduction to C++

• C++ is a programming language for manipulating


numbers and user-defined objects.
• C++ is a cross between the programming
languages C and Smalltalk.
Smalltalk C Shell programming
(objects) (numbers) (text)

C++ Perl
(numbers, objects) (text, numbers)

Java
(objects)
Variable Declaration

• Declarations need no longer be at the head of


blocks.
• Variables and functions can be declared any
time, anywhere in a program, preferably as
close to where a variable is used the first time.
• For example: note i is declared within for
for (int i=0;i<n;i++)
Global Scope

Declared at very early stage

Available at all times from anywhere

Created at the start of the program, and lasts


until the end, it is taking up lots of memory

Difficult to debug
Const Qualifier

• Used to declare “constant variables” (instead


of #define)
const float PI = 3.14156;

• The const variables must be initialized when


declared.
Reference Variable

• int i = 3;
int &r = i;

A reference variable stores the address of another


variable.

So, Is it a pointer ????? NO


Reference Variable vs Pointers

A pointer can be re-assigned any number of times while a reference can not
be reassigned after initialization.

A pointer can point to NULL while reference can never point to NULL

You can't take the address of a reference like you can with pointers

There's no "reference arithmetics" (but you can take the address of an object
pointed by a reference and do pointer arithmetics on it as in &obj + 5).

A pointer needs to be dereferenced with * to access the memory location it points to,
whereas a reference can be used directly. A pointer to a class/struct uses -> to access
it's members whereas a reference uses a ‘. ’
Pointers Vs Reference Variables

• int x = 5; int x = 5;
int y = 6; int y = 6;
int *p; int &r = x;
p = &x;
p = &y;
*p = 10;
assert(x == 5);
assert(y == 10);
int *p = NULL; int &r = NULL;
compiling error
Pointers Vs Reference Variables

int x = 5; int x = 5;
int *p = &x; int &r = x;
p++; r++;
compiling error , but can
use &r+1;
1750

5308
Comments

• double slash ”//” and terminate at the end of


line
– // this is as comment in C++

• (old C style) /* */
– /* this is an old-style comment
– which can go across multiple
– lines of code */
C++ Overview

Structure of C++ Program

Include Files

Class Definition

Class Function Definition

Main Function Program


Simple C++ Program

// Hello World program comment

#include <iostream.h> Allows access to an I/O


library

int main() {
Starts definition of special function
main()
cout << "Hello World\n";
output (print) a
string
return 0;
} Program returns a status
code (0 means OK)
Preprocessing

Temporary file
C++ (C++ program) C++
Preprocessor Compiler

Executable
C++ Program Program
Input/Output

I/O
objects
cin,
cout
Input And Output of C++
Input And Output of C++
Input And Output of C++
Input And Output of C++
Seperating Lines of Output

• New lines in output


– Recall: "\n"  "newline"
• A second method: object endl
• Examples:
cout << "Hello World\n";
• Sends string "Hello World" to display, & escape
sequence "\n", skipping to next line
cout << "Hello World" << endl;
• Same result as above
Input Using cin

• cin for input


• Differences:
– ">>" (extraction operator)
– Object name "cin" used instead of "cout"
– No literals allowed for cin
• Must input "to a variable"

• cin >> num;


– Waits on-screen for keyboard entry
– Value entered at keyboard is "assigned" to num
First C++ program …Greeting.cpp

Preprocessor // Program: Display greetings


directives Comment
#include <iostream>
#include <string>

Function int main()


named {
main() cout << "Hello world!" << endl;
indicates return 0;
start of }
program
Ends executions Insertion
of main() which ends statement
program
Output
Area.cpp

#include <iostream>

int main() {
// Extract length and width
cout << "Rectangle dimensions: ";
float Length;
float Width;
cin >> Length >> Width;

// Compute and insert the area

float Area = Length * Width;


cout << "Area = " << Area << " = Length "
<< Length << " * Width " << Width << endl;
return 0;
}
C++ Language

C++ Program is a collection of


• Tokens
• Comments
• White Space
C++ Tokens

RESERVED KEYWORDS

IDENTIFIERS

LITERALS

OPERATORS

SEPARATORS
Reserved Keywords

• Has predefined functionality


• C++ has 48 keywords
• Written in only in lower case
Reserved Keywords

delete boolean break enum


case volatile catch char
const continue default do
else asm extern union
float for auto unsigned
if inline register class
int template long double
virtual s signed goto
Protected public sizeof return
Static Struct this new
Friend Throw typedef private
try Switch while short
Identifiers

• Programmer-designed tokens
• Meaningful & short
• Long enough to understand
• C++ rules for Identifiers
- alphabets, digits, underscore
- should not start with digits.
- Case sensitive
- Unlimited length
- Declared anywhere
Literals

• Sequence of char. that represents constant


values to be stored in variables

• C++ literals are:


- Integer literals: 1,2,456,0xffff
- Floating_point literals: 4.67,3.14E-05
- Charater literals: ‘A’, ‘B’
- String literals: “ABC”, “TOTAL”
Literals ( Symbolic constants)

• Using const qualifier


ex: const int size=10;

• Using enum keyword


ex: enum{X,Y,Z};
defines const X=0;
defines const Y=0;
defines const Z=0;
Operators

• Is a symbol that takes more than one operands &


operates on them to produce a result.
- Arithmetic
- Relational
- Logical
- Assignment
- increment/Decrement
- conditional
- scope resolution(::)
- special operators: new, delete, endl, setw
Seperators

• Symbols used to indicate where groups of code


are divided & arranged
• C++ separators:
()parentheses .. Methods, precedence in exp
{} braces .. Arrays init., block of codes, scopes
; semicolon
,comma.. Separate multiple identifiers, chain
more than one stmt
. Period.. Data members, methods
[]Brackets.. Array referencing/dereferencing
C++ Statements

C++ stmts

Exp Labelled Guarding


stmt stmt stmt

Control
stmt

Selection stmt Iteration stmt Jump stmt

If contin
If switch while do for break
ue
return
else
Function Prototype

• Experience has shown that the best way to develop and


maintain large programs is to construct it from smaller
pieces(Modules)
• This technique is Called “Divide and Conquer”.
Bad Development Approach Wise Development Approach

main() main()
{
{
}
-----
-----
function f1()
.
{
.
---
----
}
-----
function f2()
Return 0;
{
}
---
}
Function Prototype

• Tells compiler argument type and return type of function

• int square( int );


• Function takes an int and returns an int

Function Call :
• functionName (argument);
or
• functionName(argument1, argument2, …);
• Example
cout << sqrt( 900.0 );
• sqrt (square root) function
• The preceding statement would print 30
• All functions in math library return a double
Function Calling

• Calling/invoking a function
– sqrt(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result

Function Name argument Output


3
cout<< sqrt(9);

Parentheses used to enclose argument(s)


Function Definition

• Syntax format for function definition


returned-value-type function-name (parameter-list)
{
Declarations of local variables and Statements
}

– Parameter list
• Comma separated list of arguments
– Data type needed for each argument
• If no arguments, use void or leave blank

– Return-value-type
• Data type of result returned (use void if nothing returned)
Function Definition

• Example function
int square( int y )
{
return y * y;
}

• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions
// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies
int square( int ); // function prototype data types of arguments and
return values. square
int main()
expects an int, and returns
{
an int.
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call

Parentheses () cause function to be called.

Function Example
cout << endl;
When done, it returns the result.
return 0; // indicates successful termination

} // end main

// square function definition returns square of an integer


int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
Definition of square. y is a
copy of the argument passed.
} // end function square Returns y * y, or y squared.

1 4 9 16 25 36 49 64 81 100
Inline Functions

• An inline function is one in which the


function code replaces the function call
directly.
• Inline class member functions
– if they are defined as part of the class
definition, implicit
– if they are defined outside of the class
definition, explicit, I.e.using the keyword,
inline.
• Inline functions should be short
(preferable one-liners).
Example of Inline Functions

class CStr
{
char *pData; Inline functions within class declarations
int nLength;

public:

char *get_Data(void) //implicit inline function
{return pData; }
int getlength(void);

};
Example of Inline Functions

inline void CStr::getlength(void) //explicit inline function


{
Inline functions outside of class declarations
return nLength;
}

int main(void)
{
In both cases, the compiler will insert the code
char *s;
of the functions get_Data() and getlength()
int n;
instead of generating calls to these functions
CStr a(“Joe”);
s = a.get_Data();
n = b.getlength();
}
Function Overloading

• Two or more functions can have the same name but


different parameters
• Example:

int max(int a, int b) { float max(float a, float b) {


if (a>= b) if (a>= b)
return a; return a;
else else
return b; return b;
} }
Default Arguments

• A default argument is a value given in the function


declaration that the compiler automatically inserts
if the caller does not provide a value for that
argument in the function call.

• Syntax:

return_type f(…, type x = default_value,…);


Default Arguments Example

• double pow(double x, int n=2)


• // computes and returns xn

• The default value of the 2nd argument is 2.


• This means that if the programmer calls pow(x),
the compiler will replace that call with pow(x,2),
returning x2
Default Arguments Rules

• Once an argument has a default value, all the


arguments after it must have default values.

• Once an argument is defaulted in a function call, all


the remaining arguments must be defaulted.

int f(int x, int y=0, int n) int f(int x, int y=0, int n=1)
// illegal // legal
Constant Arguments

• Sometimes it is the case that the programmer does


not want the actual parameters to be modified.
• In C++ we can use the const keyword to achieve
the performance of pass-by-reference while at the
same time ensuring that the actual parameter
cannot be modified.

return_type f(…, type const& var,…){ }


Constant Arguments

• The const keyword modifies the type int. It says that


the int to which x refers is a constant
• The value of x can be used without impunity.
• However, x cannot be used as the target of an
assignment statement .
• Any attempt to do so is an error that is detected by
the compiler.
Constant Arguments Example

void Two (int const& x)


{
x = 2; // Not allowed.
cout << x << endl; // This is ok.
}

• The value of x is constant and cannot be modified.


Constant Member Functions

• If you declare a class method const, you are


promising that the method won't change the value of
any of the members of the class.

return_type f([parameters]) const;


• The declaration of the constant member function
SomeFunction() takes no arguments and returns
void. It looks like this:
void SomeFunction() const;
Input Stream Functions

.get ( ) ;
Example:
char ch ;
ch = cin.get ( ) ; // gets one character from keyboard
// & assigns it to the variable "ch"

.get (character) ;
Example:
char ch ;
cin.get (ch) ; // gets one character from
// keyboard & assigns to "ch"
Input Stream Functions

.get line(array_name, max_size) ;

Example:
char name[40] ;
cin.getline (name, 40) ; // Gets up to 39 characters
// and inserts a null at the end of the
// string "name". If a delimiter is
// found, the read terminates. The
// delimiter is not stored in the array,
// but it is left in the stream.
Input Stream Functions

.read( ) ; .write( ) ;
Ex:
char gross[144] ;

cin.read(gross,144) ; // reads 144 characters from


// input stream. Does NOT
// append '\0'
New and delete operators

• new corresponds to malloc/calloc in C


• delete corresponds to free in C
• The syntax of new has forms:

–type *pointer = new type; // type is a built-in


// or user-defined data type.
–type *pointer = new type[n]; // type as above

• The semantics of this syntax is explained next


New operator

• For type *pointer = new type; :


– The system allocates dynamically (during execution) a
chunk of memory large enough to hold data of the specified
type, and returns a pointer pointing to the address of that
chunk. This pointer is stored in the user-provided pointer-
variable pointer.
New operator

• For type *pointer = new type[n]; :


– The system allocates dynamically an array of n memory
chunks, each large enough to hold data of the specified
type, and returns a pointer pointing to the address of that
chunk.

– The difference between this type of arrays (called dynamic


arrays) and conventional arrays is that the size of the latter
is constant while the size of the former can vary.
New operator

// Precondition: n is a positive integer


// Postcondition: computes and prints out the first n
// elements of the Fibonacci sequence
void fibonacci(int n){
int *x = new int [n];// creation of a dynamic array
x[0]=1; x[1]=1;
for (int i=2;i<n;i++)
x[i]=x[i-1]+x[i-2];
cout<<"The Fibonacci sequence of "<<n<<" values
are:\n";
for (int i=0;i<n;i++)
cout<<"x["<<i<<"]="<<x[i]<<endl;
}
delete operator

• The syntax of delete has two forms:

– delete pointer ;
– delete [] pointer ;

• The first releases the memory of the single memory chunk


pointed to by pointer

• The second releases the memory allocated to the array


pointed to by pointer.
delete operator

• The syntax of delete has two forms:

– delete pointer ;
– delete [] pointer ;

• The first releases the memory of the single memory chunk


pointed to by pointer

• The second releases the memory allocated to the array


pointed to by pointer.
Classes And Objects

• Defining A Class
• Data Members
• Access specifier
• Constructors
• Method Implementation in C++
• Accessing Class Member

• Destructors
Classes And Objects

• Static Data Members and Functions


• ‘this’ pointer
• Friend function
• Dynamic memory allocation
• Array Of Objects
• Pointers and Classes

• Class as ADTs
Classes And Objects

• Friend function
• Dynamic memory Allocation
•Array of Objects
•Pointers and Classes
•Class as ADTs
Classes And Objects

• Classes are user-defined (programmer-defined)


types.
– Data (data members)
– Functions (member functions or methods)

• In other words, they are structures + functions


Classes And Objects

• A class definition begins with the keyword class.


• The body of the class is contained within a set of
braces, { } ; (notice the semi-colon).

class class_name Any valid identifier


{
….
…. Class body (data
…. member + methods)
};
Class Specification
• Syntax:
class class_name
{

Data members

Members functions
};
Class Specification
• class Student
{
int st_id; Data Members or Properties of
char st_name[]; Student Class

void read_data(); Members Functions or


void print_data(); Behaviours of Student Class

};
Class Specification
• Visibility of Data members & Member functions
public - accessed by member functions and all
other non-member functions in the
program.
private - accessed by only member functions of the
class.
protected - similar to private, but accessed by
all the member functions of
immediate derived class
default - all items defined in the class are private.
Classes And Objects

class class_name
{
private:



public:



};
Classes

• Within the body, the keywords private: and


public: specify the access level of the
members of the class.
– the default is private.

• Usually, the data members of a class are


declared in the private: section of the class
and the member functions are in public:
section.
Classes

• This class example shows how we can


encapsulate (gather) a circle information into
one package (unit or class) No need for others classes to access
and retrieve its value directly. The
class Circle class methods are responsible for
{ that only.
private:
double radius;
public:
void setRadius(double r); They are accessible from outside
double getDiameter(); the class, and they can access the
double getArea(); member (radius)
double getCircumference();
};
Method Implementation

• Class implementation: writing the code of class


methods.
• There are two ways:
1. Member functions defined outside class
• Using Binary scope resolution operator (::)
• “Ties” member name to class name
• Uniquely identify functions of particular class
• Different classes can have member functions with same name
– Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}
Method Implementation

2. Member functions defined inside class


– Do not need scope resolution operator, class
name;
class Circle
{
Defined
private:
inside
double radius;
class
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Method Implementation

class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r)
{
radius = r; Defined outside class
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
Method Implementation
The second
constructor is
called

void main() Since radius is a


{ private class data
Circle c1,c2(7); member
cout<<“The area of c1:”
<<c1.getArea()<<“\n”;

//c1.raduis = 5;//syntax error


c1.setRadius(5);

cout<<“The circumference of c1:”


<< c1.getCircumference()<<“\n”;

cout<<“The Diameter of c2:”


<<c2.getDiameter()<<“\n”;
}
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
void main()
Circle::Circle(int r)
{
{ Circle c(7);
radius = r; Circle *cp1 = &c;
} Circle *cp2 = new Circle(7);
double Circle::getArea()
{ cout<<“The are of cp2:”
return radius * radius * (22.0/7); <<cp2->getArea();
}
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
} Method Implementation
Accessing Class Member

• Operators to access class members


– Identical to those for structs
– Dot member selection operator (.)
• Object
• Reference to object
– Arrow member selection operator (->)
• Pointers
• Accessing a Class Member through these operators
requires an object of the class
Objects

• Declaring a variable of a class type creates an object. You


can have many variables of the same type (class).
– Instantiation
• Once an object of a certain class is instantiated, a new
memory location is created for it to store its data
members and code
• You can instantiate many objects from a class type.
– Ex) Circle c; Circle *c;
ASSIGNMENT
Design a class Student With Its
Rollno , fees : Data member
setRollNo , displayStudentdata : Member
functions

Create two different Student objects and set


their Roll Nos and fees and display Their data
Static Data Members

• When a class field is static, only one memory


location is allocated
– All members of the class share a single storage
location for a static data member of that same class
• When you create a non-static variable within a
function, a new variable is created every time you
call that function
• When you create a static variable, the variable
maintains its memory address and previous value
for the life of the program
Static Data Members
Static Data Members

• Static variables are sometimes called class variables,


class fields, or class-wide fields because they don’t
belong to a specific object; they belong to the class
Static Function

• A static function can be used without a


declared object
• Non-static functions can access static variables
(provided there is an object)
• Static functions cannot access non-static
variables
Static Functions
‘this ‘ pointer

• The this pointer holds the memory address


of the current object that is using the function

• The this pointer is automatically supplied


when you call a non-static member function of
a class
‘this’ pointer
‘this ‘ pointer

#include <iostream.h>
class Rectangle
{
public:
Rectangle();
~Rectangle();
void SetLength(int length)
{
this->itsLength = length;
}
int GetLength() const
{
return this->itsLength;
}
void SetWidth(int width)
{
itsWidth = width;
}
‘this ‘ pointer

int GetWidth() const


{
return itsWidth;
}
private:
int itsLength;
int itsWidth;
};
Rectangle::Rectangle()
{
itsWidth = 5;
itsLength = 10;
}
Rectangle::~Rectangle() { }
‘this ‘ pointer

int main()
{
Rectangle theRect;
cout << "theRect is " << theRect.GetLength() << " feet long.\n";
cout << "theRect is " << theRect.GetWidth() << " feet wide.\n";
theRect.SetLength(20);
theRect.SetWidth(10);
cout << "theRect is " << theRect.GetLength()<< " feet long.\n";
cout << "theRect is " << theRect.GetWidth()<< " feet wide.\n";
return 0;
}
Output:
theRect is 10 feet long. theRect is 5 feet wide. theRect is 20 feet long. theRect is
10 feet wide.
Constructors
• A constructor is a special member function
whose task is to initialize the objects of its
class.
• It is special because its name is same as the
class name.
• The constructor is invoked whenever an object
of its associated class is created.
• It is called constructor because it constructs
the values of data members of the class.
Constructor - example
class add • When a class contains a
{ constructor, it is
int m, n ; guaranteed that an object
public : created by the class will be
add (void) ; initialized automatically.
}; • add a ;
add :: add (void) • Not only creates the object
{ a of type add but also
m = 0; n = 0; initializes its data members
} m and n to zero.
Constructors
continue …

• There is no need to write any statement to


invoke the constructor function.
• If a ‘normal’ member function is defined for
zero initialization, we would need to invoke
this function for each of the objects
separately.
• A constructor that accepts no parameters is
called the default constructor.
• The default constructor for class A is A : : A
()
Characteristics of Constructors
• They should be declared in the public
section.

• They are invoked automatically when the


objects are created.

• They do not have return types, not even


void and they cannot return values.
Characteristics of Constructors
continue …

• They cannot be inherited, though a derived


class can call the base class constructor.

• Like other C++ functions, Constructors can


have default arguments.

• Constructors can not be virtual.


Characteristics of Constructors
continue …

• We can not refer to their addresses.

• An object with a constructor (or destructor)


can not be used as a member of a union.

• They make ‘implicit calls’ to the operators


new and delete when memory allocation is
required.
Constructors
continue …

• When a constructor is declared for a class


initialization of the class objects becomes
mandatory.
Constructors
Syntax: Example:
class class_name class student
{
{ int st_id;
public:
class_name(); public:
}; student()
{
st_id=0;
}
};
Program
continue …
#include <iostream>

class Line
{
private:
double length;
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
};
Program
// Member functions definitions
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line:: getLength( void )
{
return length;
}
Program
int main( )
{
Line line;
line.setLength(6.0); // set line length
cout << "Length of line : " ;
line.getLength();
return 0;
}
Program Output

Object is being created


Length of line : 6
Constructors
• Pgm to create a class Addition to add two
integer values. Use constructor to initialize
values.
• Pgm to create a class Circle to compute its
area. Use constructor to initialize the data
members.
Types of Constructors
• Parameterized constructors
• Overloaded constructors
• Constructors with default argument
• Copy constructors
• Dynamic constructors
Parameterized Constructors
• It may be necessary to initialize the various
data elements of different objects with
different values when they are created.

• This is achieved by passing arguments to


the constructor function when the objects
are created.

• The constructors that can take arguments


are called parameterized constructors.
Parameterized Constructors
continue …
• When a constructor is
class add parameterized, we must pass
{ the initial values as
int m, n ; arguments to the constructor
function when an object is
public :
declared.
add (int, int) ;
------ • Two ways Calling:
}; o Explicit
• add sum = add(2,3);
add : : add (int x, int y)
o Implicit
{
• add sum(2,3)
m = x; n = y; • Shorthand method
}
Program
#include <iostream>
using namespace std;
class Line
{
private: double length;

public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
};
Program
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len<<“\n”;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
Program
int main( )
{
Line line(10.0); // get initially set length.
cout << "Length of line : " ;
cout<<line.getLength() <<endl;

// set line length again


line.setLength(6.0);
cout << "Length of line : " << line.getLength()
<<endl;
return 0; }
Program Output

Object is being created, length = 10


Length of line : 10
Length of line : 6
Using Initialization Lists to
Initialize Fields
Line::Line( double len): length(len)
{
cout << "Object is being created, length = " <<
len << endl;
}
Multiple Constructors in a
Class
• C + + permits to use more than one
constructors in a single class.

• Add( ) ; // No arguments

• Add (int, int) ; // Two arguments


Multiple Constructors in a Class
continue …

class add • The first constructor


{ receives no arguments.
int m, n ;
public :
add ( ) {m = 0 ; n = 0 • The second constructor
;} receives two integer
add (int a, int b) arguments.
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n • The third constructor
;} receives one add object as
}; an argument.
Multiple Constructors in a Class
continue …

class add • Add a1;


{ – Would automatically invoke
int m, n ; the first constructor and set
public : both m and n of a1 to zero.
add ( ) {m = 0 ; n = 0 ;} • Add a2(10,20);
add (int a, int b) – Would call the second
{m = a ; n = b ;} constructor which will
add (add & i) initialize the data members
{m = i.m ; n = i.n ;} m and n of a2 to 10 and 20
}; respectively.
Multiple Constructors in a Class
continue …

class add • Add a3(a2);


{ – Would invoke the third
int m, n ; constructor which copies the
public : values of a2 into a3.
add ( ) {m = 0 ; n = 0 ;} – This type of constructor is
add (int a, int b) called the “copy
{m = a ; n = b ;} constructor”.
add (add & i) • Construction Overloading
{m = i.m ; n = i.n ;} – More than one constructor
}; function is defined in a class.
Multiple Constructors in a Class
continue …

class complex • complex ( ) { }


{
float x, y ;
public : – This contains the empty
complex ( ) { } body and does not do
complex (float a) anything.
{x=y=a;}
complex (float r, float i)
{x=r;y=i} – This is used to create objects
------ without any initial values.
};
Multiple Constructors in a Class
continue …

• C + + compiler has an implicit constructor


which creates objects, even though it was not
defined in the class.
• This works well as long as we do not use any
other constructor in the class.
• However, once we define a constructor, we
must also define the “do-nothing” implicit
constructor.
Constructors with Default Arguments
• It is possible to define constructors with
default arguments.
• Consider complex (float real, float imag = 0);
– The default value of the argument imag is zero.
– complex C1 (5.0) assigns the value 5.0 to the real
variable and 0.0 to imag.
– complex C2(2.0,3.0) assigns the value 2.0 to real
and 3.0 to imag.
Constructors with Default Arguments
continue …

• A::A()  Default constructor


• A : : A (int = 0)  Default argument
constructor
• The default argument constructor can be
called with either one argument or no
arguments.
• When called with no arguments, it becomes a
default constructor.
Dynamic Initialization of Objects

• Providing initial value to objects at run time.

• Advantage – We can provide various initialization


formats, using overloaded constructors.

This provides the flexibility of using


different format of data at run time
depending upon the situation.
Copy Constructor

•A copy constructor is used to declare and


initialize an object from another object.

integer (integer & i) ;


integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy
constructor is known as copy initialization.
Copy Constructor
continue …

The statement
I 2 = I 1;
will not invoke the copy constructor.

If I 1 and I 2 are objects, this statement is legal


and assigns the values of I 1 to I 2, member-by-
member.
Copy Constructor
continue …

• A reference variable has been used as an


argument to the copy constructor.

• We cannot pass the argument by value to a


copy constructor.
Dynamic Constructors

• The constructors can also be used to allocate


memory while creating objects.

• This will enable the system to allocate the


right amount of memory for each object
when the objects are not of the same size.
Dynamic Constructors
continue …

• Allocation of memory to objects at the time


of their construction is known as dynamic
construction of objects.

• The memory is created with the help of the


new operator.
Overloaded Constructors
class Addition
{
int num1,num2,res;
float num3, num4, f_res;
public:
Addition(int a, int b); // int constructor
Addition(float m, float n); //float constructor
void add_int( );
void add_float();
void print();
};
Constructors with Default Argument
class Addition
{
int num1;
int num2;
int res;
public:
Addition(int a, int b=0); // constructor
void add( );
void print();
};
Copy Constructor
class code
{
int id;
public:
code() //constructor
{ id=100;}
code(code &obj) // constructor
{
id=obj.id;
}
};
Dynamic Constructors
class Sum_Array
{
int *p;
public:
Sum_Array(int sz) // constructor
{
p=new int[sz];
}
};
Destructors

• A destructor is used to destroy the objects


that have been created by a constructor.

• Like constructor, the destructor is a member


function whose name is the same as the
class name but is preceded by a tilde.
eg: ~ integer ( ) { }
Destructors
continue …

• A destructor never takes any argument nor


does it return any value.

• It will be invoked implicitly by the compiler


upon exit from the program – or block or
function as the case may be – to clean up
storage that is no longer accessible.
Destructors
continue …

• It is a good practice to declare destructors in


a program since it releases memory space
for further use.

• Whenever new is used to allocate memory


in the constructor, we should use delete to
free that memory.
Destructor

• Destructors
– Special member function
– Same name as class
• Preceded with tilde (~)
– No arguments
– No return value
– Cannot be overloaded
– Before system reclaims object’s memory
• Reuse memory for new objects
• Mainly used to de-allocate dynamic memory locations
Destructor

Destructor
Example Of Destructor

void Time::printTime(){
cout<<"The time is :
"<<*hour<<":"<<*minute<<":"<<*second<<")"
<<endl;
}
Destructor: used here to de-allocate
Time::~Time() memory locations
{
delete hour; delete minute;delete second;
}
Output:
void main()
{
The time is : (3:55:54)
Time *t; The time is : (7:17:43)
t= new Time(3,55,54); Press any key to continue
t->printTime();
t->setHour(7);
t->setMinute(17);
t->setSecond(43); When executed, the destructor
t->printTime(); is called
delete t;}
Programs for Implementation
• Pgm to create a class Complex to add two
complex numbers using parmeterized
constructor.
• Pgm to create a class Complex to add two
complex numbers using copy constructor.
• Pgm to create a class Complex to add
dynamically created integer to a complex
number using Dynamic constructor.
Who is a friend ?

A friend is a one who has access to all your “ PRIVATE” Stuff


Friend function

• C++ friend functions are special functions


which can access the private members of a
class.
How is it different from a normal
function?
• A member is “access” through the “object”

Ex : sample object;
object.getdata( );

• Whereas a friend function requires object to be passed


by value or by reference as a parameter

Ex : sample object;
getdata(object) ;
Friend Functions
Example:
class myclass
{
int a, b;
Syntax:
public:
class class_name
friend int sum(myclass x);
{
void set_val(int i, int j);
//class definition
};
public:
friend rdt fun_name(formal parameters);
};
Code Snippet
class demo
{
int x ;
public :
demo(int xxx)
{ int main( )
x = xxx;
}
{
friend void display(demo) ; demo d(5);
}; display(d);
void display(demo d1) return 0;
}
{
cout<<dd1.x;
}
Friend function

Friend functions have the following properties:

• 1) Friend of the class can be member of some other class.


• 2) Friend of one class can be friend of another class or all the classes in one
program, such a friend is known as GLOBAL FRIEND.

• 3) Friend can access the private or protected members of the class in which they
are declared to be friend, but they can use the members for a specific object.

• 4) Friends are non-members hence do not get “this” pointer.

• 5) Friends, can be friend of more than one class, hence they can be used for
message passing between the classes.
• 6) Friend can be declared anywhere (in public, protected or private section) in the
class.
Program for Implementation
Pgm to create a class ACCOUNTS with function
read() to input sales and purchase details.
Create a Friend function to print total tax to
pay. Assume 4% of profit is tax.
Friend Class

• A class can also be declared to be the friend of


some other class.
• When we create a friend class then all the
member functions of the friend class also
become the friend of the other class
• This requires the condition that the friend
becoming class must be first declared or
defined (forward declaration).
Friend Class

#include <iostream>

class MyClass
{
private:
int Secret;

// Declare a friend class


friend class SecondClass;

public:
MyClass() : Secret(0){}
void printMember()
{
cout << Secret << endl;
}
};
Friend Class

class SecondClass
{
public:
void change( MyClass& yourclass, int x )
{
yourclass.Secret = x;
}
};

void main()
{
MyClass my_class;
SecondClass sec_class;
my_class.printMember();
sec_class.change( my_class, 5 );
my_class.printMember();
}
Arrays of Objects
• Several objects of the same class can be
declared as an array and used just like an array
of any other data type.

• The syntax for declaring and using an object


array is exactly the same as it is for any other
type of array.
Array Of Objects

• Arrays of variables of type "class" is known as


"Array of objects".

• The "identifier" used to refer the array of


objects is an user defined data type.
Example Of Array Of Objects

#include <iostream.h>
const int MAX =8;
class Student
{
private: int roll;
char *name;
public:
void read_data( )
{
cout << "\n Enter the RollNo:";
cin >> roll;
cout << "\n Enter the name:";
cin >> name;
}
Example Of Array Of Objects

void print_data( )
{
cout << “Students Roll No is " << roll << "and name
is" << name << endl;
}
}; //class Detail ends
void main()
{
Student st[MAX]; //Array of objects of Detail class
int n=0;
Example Of Array Of Objects

char ans;
do
{
cout << "Enter the Info of Student ::" << n+1;
st[n++].read_data( );
cout << "Enter another (y/n)?: " ;
cin >> ans;
} while ( ans != 'n' );
for (int j=0; j<n; j++)
{
cout << "\n Info of Employee " << j+1<<“ is:: ”;
st[j].print_data( );
}
} // main ends
Class Objects
33, Joseph

• Avoridrreayad_odaftaO
( ) bjects
St[0]
ex: Student st[8]; St[1]
void print_data( )
St[2]
S t[0]
24, Sak sh i St[3]
void read_data( ) St[4]
void print_data( )
St[5]
St[6]
St[4] St[7]
Program for Implementation
Pgm to create a class STUDENT with
properties: rollno, name, IAmarks for 6
subjects, EndExamMarks for 6 subjects. Create
function read() to read the details of student,
calc_percent() to calculate the percentage
marks for each student and show() to display
the details of all students. Assume the
following things to calculate percentage:
Total_sub_marks = IAmarks + EndExamMarks
& Total_marks = Addition of Total_sub_marks
of 6 subjects.
Pointers to Objects
student st; 51, Rajesh

student *ptr; void read_data( )

ptr = & st; void print_data( )

2FCD54

ptr st
Pointers to Objects
“Pointers can be defined to hold the address
of an object, which is created statically or
dynamically”.
33, Joseph Statically created object:
student *stp;
void read_data( )
stp = &st;
void print_data( )
Dynamically created object:
student *stp;
st stp = new student;
2FCDA4
Pointers to Objects
• Accessing Members of objects:
Syntax:
ptr_ob j  member_name;
ptr_obj  memberfunction_name( );

Example:
stp  st_name;
stp  read_data ( );
New and delete operators

• new corresponds to malloc/calloc in C


• delete corresponds to free in C
• The syntax of new has forms:

–type *pointer = new type; // type is a built-in


// or user-defined data type.
–type *pointer = new type[n]; // type as above

• The semantics of this syntax is explained next


New operator

• For type *pointer = new type; :


– The system allocates dynamically (during execution) a
chunk of memory large enough to hold data of the specified
type, and returns a pointer pointing to the address of that
chunk. This pointer is stored in the user-provided pointer-
variable pointer.
New operator

• For type *pointer = new type[n]; :


– The system allocates dynamically an array of n memory
chunks, each large enough to hold data of the specified
type, and returns a pointer pointing to the address of that
chunk.

– The difference between this type of arrays (called dynamic


arrays) and conventional arrays is that the size of the latter
is constant while the size of the former can vary.
New operator

// Precondition: n is a positive integer


// Postcondition: computes and prints out the first n
// elements of the Fibonacci sequence
void fibonacci(int n){
int *x = new int [n];// creation of a dynamic array
x[0]=1; x[1]=1;
for (int i=2;i<n;i++)
x[i]=x[i-1]+x[i-2];
cout<<"The Fibonacci sequence of "<<n<<" values
are:\n";
for (int i=0;i<n;i++)
cout<<"x["<<i<<"]="<<x[i]<<endl;
}
Manipulators

• C++ provides various stream manipulators that


perform formatting tasks.
• Stream manipulators are defined in <iomanip>
• These manipulators provide capabilities for
– setting field widths,
– setting precision,
– setting and unsetting format flags,
– flushing streams,
– inserting a "newline" and flushing output stream,
– skipping whitespace in input stream
Manipulators

setprecision ( ) / precision( )
• Select output precision, i.e., number of significant digits to be
printed.
• Example:
cout << setprecision (2) ; // two significant digits
OR
cout.precision(2);
setw ( )
• Specify the field width (Can be used on input or output, but
only applies to next insertion or extraction).
• Example:
cout << setw (4) ; // field is four positions wide
Manipulators

setw ( )
• Specify the field width (Can be used on input or output, but
only applies to next insertion or extraction).
• Example:
cout << setw (4) ; // field is four positions wide
Manipulators

• Various ios format flags specify the kinds of formatting to be


performed during stream I/O.

• There are member functions (and/or stream manipulators)


which control flag settings.

• There are various flags for trailing zeros and decimal points,
justification, number base, floating point representation, and
so on.
Manipulators

ios::showpoint when set, show trailing decimal


point and zeros

ios::showpos when set, show the + sign before


positive numbers

ios::basefield
ios::dec use base ten
ios::oct use base eight
ios::hex use base sixteen
Manipulators

ios::floatfield
ios::fixed use fixed number of digits
ios::scientific use "scientific" notation

ios::adjustfield
ios::left use left justification
ios::right use right justification
ios::internal left justify the sign, but right
justify the value
Manipulators

.setf ( )
• Allows the setting of an I/O stream format flag.

• Examples:
// To show the + sign in front of positive numbers
cout.setf (ios::showpos) ;

// To output the number in hexadecimal


cout.setf (ios::hex, ios::basefield) ;
Manipulators

.precision ( ) ;
• Select output precision, i.e., number of significant digits to be
printed.
• Example:
cout.precision (2) ; // two significant digits

.width ( ) ;
• Specify field width. (Can be used on input or output, but only
applies to next insertion or extraction).
• Example:
cout.width (4) ; // field is four positions wide
Manipulators

#include <iostream> // No “.h” (standard header)


#include <iomanip> // No “.h” (standard header)
using namespace std; // To avoid “std::”
int main ( )
{
int a, b, c = 8, d = 4 ;
float k ;
char name[30] ;
cout << "Enter your name" << endl ;
cin.getline (name, 30) ;
cout << "Enter two integers and a float " << endl ;
cin >> a >> b >> k ;
Manipulators

// Now, let's output the values that were read in


cout << "\nThank you, " << name << ", you entered"
<< endl << a << ", " << b << ", and " ;
cout.width (4) ;
cout.precision (2) ;
cout << k << endl ;
// Control the field and precision another way
cout <<"\nThank you, " << name << ", you entered"
<< endl << a << ", " << b << ", and " << setw (c)
<< setprecision (d) << k << endl ;
}
Manipulators Program Output

Enter your name


K. S. Kotecha
Enter two integers and a float
12 24 67.85

Thank you, K. S. Kotecha, you entered


12, 24, and 68

Thank you, K. S. Kotecha, you entered


12, 24, and 67.85

You might also like