0% found this document useful (0 votes)
19 views62 pages

Unit 2

Uploaded by

Himesh Kochale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views62 pages

Unit 2

Uploaded by

Himesh Kochale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

UNIT-2

Functions and Constructors


MARKS-16
Array of objects

• Dot member operator is used to access


member functions
• Index is used to represent elements of array
• Syntax:
Class_name object_name[Array limit];
Example
Class Staff Void main()
{ {
Public: Int I;
Char name[20],dept[20]; Clrscr();
Void accept() Staff s[10];
{ For(i=0;i<=9;i++)
cout<<“Enter Name and {
Depart”;
s[i].accept();
Cin>>name>>dept;
}
}
Void display()
Cout<<“Nmae\t Department\n”;
{ For(i=0;i<=9;i++)
cout<<name<<“\t”<<dept<<\n; {
} s[i].display();
}
getch();
}; }
Object as a Function Argument
• Arrays can be used as function arguments
• 2 ways:
1. Pass by value: copy of entire object is passed to
function so any changes made to object inside
function do not affect object used to call function.

2. Pass by reference: address of object is passed to


function so any changes made to object inside
function will affect object used to call function.
Pass By Value
#include<iostream> Void time:: sum(time t1,time t2)
Using namespace std; {
minutes=t1.minutes + t2.minutes;
Class time Hours=minutes/60;
{ Minutes=minutes%60;
int hours; Hours=hours+t1.hours +t2.hours;
int minutes; }

Public: int main()


Void gettime(int h,int m) {
{ time t1,t2,t3;
Hours=h; t1.gettime(2,45);
Minutes=m; T2.gettime(3,30);
}
Void puttime(void) T3.sum(t1,t2);
{
cout<<hours<<“hours and”; Cout<<“t1=”;t1.puttime();
Cout<<minutes<<“minutes”<<“\n”; Cout<<“t2=”;t2.puttime();
} Cout<<“t3=”;t3.puttime();
void sum(time, time); Return 0;
}; }
Output
• T1=2 hours and 45 minutes
• T2=3 hours and 30 minutes
• T3=6 hours and 15 minutes
Pass By Reference
#include<iostream>
using namespace std; cout<<"\nTOURIST NAME : "<<name;
class Tourist cout<<"\nAMOUNT PAID : "<<amount;
{ }
int id;
char name[30]; void modify(Tourist &t,float new_amt)
float amount; {
public: t.amount=new_amt;
cout<<"\tNEW AMOUNT FOR TOURIST "<<t.id<<"
void get_input(void);
IS : "<<t.amount;
void modify(Tourist&,float);
}
void display(void);
}; int main()
void Tourist::get_input() {
{ float amt;
cout<<"ENTER TOURIST ID : "; Tourist t1;
cin>>id; t1.get_input();
cout<<"ENTER NAME : "; cout<<"\n\n--BEFORE MODIFICATION--";
cin>>name; t1.display();
cout<<"ENTER AMOUNT PAID : "; cout<<"\n\n\tENTER THE NEW AMOUNT : ";
cin>>amount; cin>>amt;
} modify(t1,amt);
void Tourist::display() cout<<"\n\n\n--AFTER MODIFICATION--";
{ t1.display();
Output
ENTER TOURIST ID : 11
ENTER NAME : siddharth
ENTER AMOUNT PAID : 1900
--BEFORE MODIFICATION--
TOURIST ID : 11
TOURIST NAME : siddharth
AMOUNT PAID : 1900
ENTER THE NEW AMOUNT : 2100
NEW AMOUNT FOR TOURIST 11 IS : 2100
--AFTER MODIFICATION--
TOURIST ID : 11
TOURIST NAME : siddharth
AMOUNT PAID : 2100
Accessing members of object within a called
function
Static data members

• Static variables are initializes to zero when


objects are created.

• When member variable is declared as static it


tells compiler that one copy of variable will
exist and all objects of class will share that
variable
• Characteristics:
1. It initialized to zero when first object is
created. No other initialization is permitted
2. Only one copy of that data member is created
for entire class.
3. Visible only within class
4. Generally used to maintain values common to
entire class
• Static data members are not stored as a part of
object.
• type and scope of variable must be defined
outside class definition.
• Syntax:
data-type class-name::static-variable-name;
• This is called definition of static member.
• E.g.
class item
{
static int count; //count is static
public:
--------------------
---------------------
};
int item :: count; //definition of static data
member
Program
//Code to demonstrate how a static data member can be accessed with the help
//of a static member function
#include <bits/stdc++.h>
using namespace std;
class A {
// Declaration
static int x;
public:
// Static member function.
static int increment() {
return ++x;
}
};

// Definition
int A::x = 1;

int main() {
A a;
// Accessing static data member using static member function.
cout << a.increment();
}
Static member function

• Properties:
1. Static member function can have access to
only other static members declared in same
class

2. Static member function can be called using


class name as follows:
class-name::function-name;
Example
class Note
{
static int num;

public:
static int func ()
{
cout << " The value of the num is: " << num << endl;
}
};
// initialize the static data member
int Note :: num = 15;

int main () Output:


{ The value of the num is: 15
Note n;
n.func();
return 0;
}
Before studying friend functions
class MyClass {
int num1, num2; public:
void initialize( );
int average(MyClass s);
};
void MyClass::initialize( ){
num1 = 10;
num2 = 20;}
int average(MyClass s){
return((s.num1+s.num2)/2);}
int main(){
MyClass x;
x.initialize();
cout<<"Average:"<<average(x); return(0);
}
Friend Functions
[W08]
• Private member can not be accessed from outside
class

• If situation occurs that two classes have to share


function in such cases common function to be made
friendly with 2 classes.

• To make outside function “friendly” simply declare


this function as a friend of the class.
Class xyz
{
………
………
public:
………
………
friend void abc(); //declaration
};
• Function definition does not use either keyword
friend or scope resolution operator(::)

• Function declared with keyword friend are called as


“friend functions” .

• Can be declared as friend in any no of classes


Characteristics of friend function
• It is not in the scope of the class to which it has been declared
as 'friend'.

• Since it is not in the scope of the class, it can not be called


using object of the class. Called like a normal function.

• Unlike member functions, it can not access the member


names directly and has to use an object name and dot
membership operator with each member name (e.g. obj.x).

• It can be declared either in public or the private part of the


class without affecting its meaning.
• Usually, it has objects as arguments.
Example
#include <iostream>
using namespace std; int main()
class Box
{
{
private: Box b;
int length; cout<<"Length of box: "
public: << printLength(b)<<endl;
Box(): length(0) { }
friend int printLength(Box); // return 0;
friend function
};
}
int printLength(Box b)
{ • Output:
b.length += 10;
return b.length;
• Length of box: 10
• Friend class:
it is also possible to declare all member functions of
one class as friend function of another class. That
class is called “Friend Class”.
Class X
{
---------
friend class Y; //all member functions of Y are
friends to X
};
• Compiler will not acknowledge presence of
another class unless its name is declared in
beginning (forward declaration)
Program
#include <iostream>
using namespace std;
int main()
class B;
class A
{
{ A a;
int x =5; B b;
friend class B; // friend class. b.display(a);
};
return 0;
class B }
{
public:
void display(A &a)
{
Output:
cout<<"value of x is : "<<a.x;
}
}; value of x is : 5
Constructors and
Destructors
Introduction
• Earlier, we initialize data members using functions
like input(),accept() or getdata().
e.g. a.getdata();

Or invokes function bypassing values as arguments


e.g. a.input(20,30);

All these values are assigned to members after creation


of objects and not used at the time of creation of
objects.
• The main use of constructors is to initialize objects.

• The function of initialization is automatically carried


out by the use of a special member function called a
constructor.

• Destructors are special member function used to


release dynamically allocated memory of objects
when object is no longer used.
Constructor

• Its task is to initialize objects of its class.


• Special – because its name is same as class
name
• Constructor is invoked whenever objects of
class is created
• Called as constructor because it constructs
values of data members of class
• // class with constructor • When object is created
class time like
{ time t1;
int hr,min;
public: It not only creates an
time(); object t1 but also initialize
}; its data members hr, min to
time::time() zero.
{
hr=0; **no need to write any
min=0 statement to invoke
} constructor
Characteristics
1. They should be declared in public section

2. They are invoked automatically when the objects are


created.

3. They do not have return types, not even void and they
cannot return values

4. They cannot be inherited, though a derived class can


call the base class constructor.
5. Constructors can have default arguments.
6. We can not refer to their addresses.
7. They make ‘implicit calls’ to the operators
new and delete when memory allocation is
required.
Types of constructor
1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Dynamic constructor
Default constructor
• This constructor has no arguments in it.
• Default Constructor is also called as no
argument constructor.
• Default constructor of class Time is
Time::Time()
• If no such constructor is defined. Compiler
supplies default constructor.
• Statement like Time t; invokes default
constructor to create object t
Example
class creature void main()
{
{
private:
int yearofBirth; creature obj;
Public: getch();
creature() ; }
};
creature::creature()
{
cout<<“Contructor called";
}
Parameterized Constructors
• A parameterized constructor is just one that
has parameters specified in it.
• We can pass the arguments to constructor
function when object are created.
• A constructor that can take arguments are
called parameterized constructors.
// constructor with parameters When constructor is
class time parameterized, object
{ creation like
int hour,minute; time t1;
public:
time(int hr,int min); may not work.
}; We must pass initial values
time::time(int hr,int min) as arguments to constructor
{ when object is declared.
hour=hr;
minute=min;
}
1. By calling constructor explicitly
2. By calling constructor implicitly

3. Explicit call
time t1=time(3,45);
2. Implicit call : also called shorthand method
time t1(3,45);
• Constructor function can be defined as inline function.
class time
{
int hr,min;
public:
time(int hr,int min) //inline constructor
{
hour=hr;
minute=min;
}
};
Parameterized constructor program
#include <iostream> void display ()
using namespace std; {
class Professor cout<<id<<" "<<name<<"
"<<salary<<endl;
{
}
public:
};
int id;
int main(void)
string name; {
float salary; Professorp1=Professor(10,
Professor (int i, string n, float s) "Aditya", 90000);
{ Professor p2=Professor(12,
id = i; "Anu", 60000);
name = n; p1.display();
salary = s; p2.display();
return 0;
}
}
Output
Copy constructor
• A constructor can accept a reference to its own
class as a parameter which is called copy
constructor.
class time
{
-------
public:
time(time &); //copy constructor
};
• Copy Constructor is used to declare and initialize an
object from another object.
• For example the statement:

• abc c2(c1);
• would define the object c2 and at the same time
initialize it to the value of c1.

• The process of initializing through a copy constructor


is known as copy initialization.
• Note:
Reference variable is used as an argument
to the copy constructor but we cannot pass
value as an argument to copy constructor.
Program
#include <iostream> int main()
using namespace std; {
class A A a1(20);
{ // Calling the parmeterized construct
public: or.
int x;
A(int a) // parameterized co A a2(a1);
nstructor.
{ // Calling the copy constructor.
x=a;
} cout<<a2.x;
A(A &i) // copy constructor return 0;
{ }
x = i.x;
} • Output:
};
20
Dynamic constructor
• 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.

• 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.
Program
#include <iostream>
using namespace std; int main()
{
class geeks geeks obj;
{
obj.display();
const char* p;
}
public:

geeks()
{
Output:
// allocating memory
at run time geeks
p = new char[6];
p = "geeks";
}

void display()
{
cout << p << endl;
}
};
Multiple Constructors in a class
• We have studied three types of constructors
i.e. constructor with no argument,
parameterized constructor and copy
constructor.
time(); //no arguments
time(int,int); //two arguments
time(time &t); //copy constructor
time(int h,int m) //constr. 2
class time
{
{ hr=h;
int hr,min; min=m;
public: }
time(time &t) //constr. 3
time() //constr. 1 {
{ hr=t.hr;
hr=0; min=0; min=t.min
}
}
};
• In first constructor itself supplies value and no
values are passed by calling program
• In second function call passes values to
constructor from main().
• In third, it receives one object as an argument
In main:
• time t1; invokes first constructor and set hr
and min to zero.
• time t2(3,45); invokes second constructor and
set hr and min to 3 and 45 respectively.
• time t3(t2); invokes third constructor and
copies values of t2 to t3.
• C++ allows us to use more than one constructor
in same class.
Overloading of constructors
• When more than one constructor used in
same class, then constructors are overloaded.
Program
#include <iostream>
using namespace std;

class construct int main()


{ {
// Constructor
public: Overloading
float area; // with two different
constructors
// Constructor with no parameters
construct()
// of class name
{ construct o;
area = 0; construct o2( 10, 20);
}
o.disp();
// Constructor with two parameters o2.disp();
construct(int a, int b)
return 1;
{
area = a * b; }
}
Output:
void disp()
{ 0
cout<< area<< endl; 200
}
};
Constructors with Default Arguments
• It is possible to define constructors with
default arguments.
• Default argument is an argument to a function
that a programmer is not required to specify.
• C++ allow the programmer to specify default
arguments that always have a value, even if
one is not specified when calling the function.
• For example, in the following function declaration:
void input(int a, int b, int c=12);
• The programmer may call this function in two ways:
a.input (1, 2, 3);
a.input(1, 2);
• In the first case the value for the argument called c is
specified as normal. In the second one, the argument is
omitted, and the default value of 12 will be used
instead.
• It is possible to define constructors with default
arguments
• A::A()  Default constructor
• A : : A (int i = 7)  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.
Destructors
• A destructor is used to destroy the objects
that have been created by a constructor.
• Destructors are special member functions -
Takes the same name of class name.
• Release dynamic allocated memory.
• General Syntax:
~ classname();
e.g. ~time();
Characteristics
• It takes the same name as class name.
• It should be defined in the public section.
• Destructors cannot be overloaded.
• A destructor never takes any argument
• No return type is specified.
Program
main()
#include <iostream>
using namespace std; {
class Test Test t, t1,
{ return 0;
public: }
Test()
{ Output:
cout << "\n Constructor
executed"; Constructor executed
} Constructor executed
Destructor executed
~Test()
{ Destructor executed
cout << "\n Destructor
executed";
}
};
Thank You

You might also like