Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

C++ Programming Unit IV

Uploaded by

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

C++ Programming Unit IV

Uploaded by

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

Unit – IV

Functions & Objects

Passing Objects as Arguments: In C++, an object is treated as a built in data type. An object
can be used as a function argument. It can be done in the following two ways:

(a) Pass by value (b) Pass by reference

(a) Pass by value: A copy of the object is passed to the function and any change made is not
reflected back. An object may be passed by value to a member function, a non member function and
a friend function.

Example

#include<iostream.h>
#include<conio.h>
class sum
{
private:
int a, b;
public:
void get_value( )
{
cout<<”\n Enter the Values:-“;
cin>>a>>b;
}
void add(sum s1, sum s2)
{
int x, y;
x = s1.a + s2.a;
y = s1.b + s2.b;
cout<<”\n Values after addition :-“;
cout<<”\nX =” <<x << ”\nY =” <<y;
}
};
void main( )
{
sum ob, ob1, ob2;
clrscr( );
ob1.get_value( );
ob2.get_value( );
ob.add(ob1, ob2);
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 1 of 25


(b) Pass by reference: The memory address of the object is passed to the function and the
called function operates on the original object being passed. No separate memory is allocated for the
data members of the passed object.

Example

#include<iostream.h>
#include<conio.h>

class sum
{
private:
int a, b, c;
public:
void get_value(sum &obj)
{
cout<<”\n Enter the Values:-“;
cin>>obj.a>>obj.b>>obj.c;
}
void add(sum &s1, sum &s2)
{
int x, y, z;
x = s1.a + s2.a;
y = s1.b + s2.b;
z = s1.c + s2.c;
cout<<”\n Values after addition :-“;
cout<<”\nX =” <<x;
cout<<”\nY =” <<y;
cout<<”\nZ =” <<z;
}
};

void main( )
{
sum ob, ob1, ob2;
clrscr( );
ob.get_value(ob1);
ob.get_value(ob2);
ob.add(ob1, ob2);
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 2 of 25


Functions returning Object: In C++, objects can not only be passed to function but object
can be returned also from functions.

Example:
#include<iostream.h>
#include<conio.h>
class plus
{
private:
int a, b, c;
public:
plus( int x, int y, int z)
{
a = x;
b = y;
c = z;
}
friend plus operator + (plus, plus);
void show( );
};

plus operator +(plus e, plus d)


{
plus temp;
temp.a = e.a + d.a;
temp.b = e.b + d.b;
temp.c = e.c + d.c;
return temp;
}

void plus::show( )
{
cout << “\n The value of a is :-“ << a;
cout << “\n The value of b is :-“ << b;
cout << “\n The value of c is :-“ << c;
}

void main( )
{
clrscr( );
plus ob(5, 15 ,17), ob1(2, 7, 9), ob2;
cout << “\n The values after plus operator are:-“
ob2 = ob + ob1;
ob2.show( );
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 3 of 25


Inline Functions: C++ inline function is powerful concept that is commonly used with classes.
All the member functions defined inside the class definition are by default declared as Inline, but we can
also make any non-class function inline by using keyword inline with them. If a function is inline, the
compiler places a copy of the code of that function at each point where the function is called at compile
time.
Return_type
Syntax |
inline |function_name( )
{
//function body
}

Example

#include<iostream.h>
#include<conio.h>

inline void show( )


{
cout<<"Hello world";
}

void main( )
{
show( ); // Call it like a normal function
getch( );
}

Inline Functions Advantages:

• Function call overhead doesn’t occur.


• 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.
• Inline function may be useful (if it is small) for embedded systems.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 4 of 25


Friend Functions: A friend function of a class is defined outside that class scope but it has the
right to access all private and protected members of the class. A friend can be a function, function template,
or member function, or a class or class template, in which case the entire class and all of its members are
friends.

For accessing the data, the declaration of a friend function should be done inside the body of a class starting
with the keyword friend.

Syntax

class class_name

{
friend data_type function_name(arguments);
};

Example
#include<iostream.h>
#include<conio.h>
class Box
{
private:
int length;

public:

Box ( )
{
length = 0;
}

friend int printlen(Box); // Declaration of friend function


};
int printlen(Box b)
{
b.length = b.length + 10;
return b.length;
}
void main( )
{
Box obj;
int res;
res = printlen(obj);
cout<<”Length of Box:- “<< res;
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 5 of 25


Characteristics of Friend Function

• Friend function can be declared anywhere in the class.


• Friends, can be friend of more than one class, hence they can be used for message passing between
the classes.
• It can be invoked like a normal function without any object.
• Friends are non-members hence do not get “this” pointer.
• Friend can access the private or protected members of the class in which they are declared to be
friend.

Abstract Class: Abstract Class is a class which contains atleast one Pure Virtual function in it.
Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class
must provide definition to the pure virtual function, otherwise they will also become abstract class.

Characteristics of Abstract Class

1. Abstract class cannot be instantiated, but pointers and references of Abstract class type can be
created.
2. Abstract class can have normal functions and variables along with a pure virtual function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will
become Abstract too.

Example

#include <iostream.h>
#include <conio.h>
class Shape
{
protected:
float l;
public:
void getData( )
{
cin >> l;
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 6 of 25


virtual float calculateArea( ) = 0; // pure virtual Function
};
class Square : public Shape
{
public:
float calculateArea( )
{ return l*l; }
};
class Circle : public Shape
{
public:
float calculateArea( )
{ return 3.14*l*l; }
};
void main()
{
Square s;
Circle c;
cout << "Enter length to calculate the area of a square: ";
s.getData( );
cout<<"Area of square: " << s.calculateArea( );
cout<<"\nEnter radius to calculate the area of a circle: ";
c.getData( );
cout << "Area of circle: " << c.calculateArea( );
}

Function/Method Overriding: Method overriding, in object-oriented programming, is a


language feature that allows a subclass or child class to provide a specific implementation of a method that
is already provided by one of its super classes or parent classes.

Conditions for Function Overriding

• Functions of both parent and child class must have the same name.
• Functions must have the same argument list and return type.
• A function declared static cannot be overridden.
• If a function cannot be inherited, it cannot be overridden.

In function overriding when an object of the derived class is created and it call the member function which
exists in both classes (base and derived), the member function of the derived class is invoked and the
function of the base class is ignored.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 7 of 25


Example

#include <iostream.h>
#include<conio.h>
class BaseClass
{
public:
void disp( )
{
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass
{
public:
void disp( )
{
cout<<"Function of Child Class";
}
};

void main( )
{
DerivedClass obj;
obj.disp( );
getch( );
}

variables of
|
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 the 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.

A constructor is declared and defined as follows:

class student
{
int roll_no;
float marks;
public:
student( ) // constructor
{
roll_no = 0;
marks = 0.0;
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 8 of 25


.
. // other public members
.
};
int main( )
{
student s1; // object created
.
.
.
}

Types of Constructors:

Constructors are of three types


(a) Default Constructor (b) Parameterized Constructor (c) Copy Constructor
(a) Default Constructor: A constructor that accepts no parameter is called the default
constructor.

Example:
#include<iostream.h>
#include<conio.h>
class code
{
int roll_no;
float marks;
public:
code( ) // default constructor
{
roll_no = 1;
marks = 2.5;
}

void display( void )


{
cout << roll_no;
cout << marks;
}
};
int main( )
{
code A( ); // default constructor called

cout << “\n id of A : “ << A.display( );


}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 9 of 25


(b) Parameterized Constructor: The constructors that can take arguments are called
parameterized constructors.

Example:
#include<iostream.h>
#include<conio.h>

class code
{
int roll_no;
float marks;
public:
code( int a, float b) // parameterized constructor
{
roll_no = a;
marks = b;
}

void display( void )


{
cout << roll_no;
cout << marks;
}
};

int main( )
{
code A(100, 10.5); // parameterized constructor called

cout << “\n id of A : “ << A.display( );

(c) Copy Constructor: A copy constructor is a constructor that defines and initializes an
object with another object. It takes the form classname (classname &).

Example:
#include<iostream.h>
#include<conio.h>

class code
{
int id;
public:
code( int a) // parameterized constructor
{

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 10 of 25


id = a;
}

code( code &z) // copy constructor


{
id = z.id;
}

void display( void )


{
cout << id;
}
};

int main( )
{
code A(100);
code B(A); // copy constructor called

cout << “\n id of A : “ << A.display( );


cout << “\n id of B : “ << B.display( );
}

Characteristics of Constructors:

(a) They should be declared in the public section.


(b) They are invoked automatically when the objects are created.
(c) They do not have return types not even void.
(d) They cannot be inherited, though a derived class can call the base class constructor.
(e) A constructor may not be static.
(f) It is not possible to take the address of a constructor.
(g) Constructors cannot be virtual.

Destructors: A destructor, as the name implies, is used to destroy the objects that have been created
by a constructor. Like a constructor, the destructor is also a member function whose name is the same as the
class name but is preceded by a tilde (~). It is called automatically by the complier when an object is
destroyed. A destructor cleans up the storage (memory area of the object) that is no longer accessible.

Following code fragment gives an example of a destructor:


class sample
{

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 11 of 25


int i, j;
public:
sample (int a, int b) // constructor
{
i = a;
j = b;
}

~sample ( ) // destructor
{
cout << “ Destructor at work \n”;
}
};

int main( )
{
sample s1(50, 100);
}

Need for Destructors:

During construction of an object by the constructor, resources may be allocated for use. For example, a
constructor may have opened a file and a memory area may be allotted to it. Similarly, a constructor may
have allocated memory to some other objects. These allocated resources must be deallocated before the
object is destroyed. A destructor will work here for this task and performs all clean-up tasks (like closing a
file, deallocating and releasing memory area) automatically. Therefore, a destructor is equally useful as a
constructor is.

Characteristics of Destructors:

(a) They are invoked automatically when the objects are destroyed.
(b) A destructor never takes any argument nor does it return any value.
(c) They cannot be inherited.
(d) A destructor may not be static.
(e) It is not possible to take the address of a destructor.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 12 of 25


Static Data Members and Methods:

Static Data Members: Static data members of class are those members which are shared by all the
objects. Static data member has a single piece of storage, and is not available as separate copy with each
object, like other non-static data members.

Static member variables (data members) are not initialized using constructor, because these are not
dependent on object initialization.

It is initialized to zero when the first object of its class is created. All the static members must be defined
outside the class definition.

Example:

#include <iostream.h>
#include <conio.h>
class item
{
static int count;
int num;

public:
item( )
{
num = 0;
}

void get_data( int a)


{
num = a;
count++;
}

void getcount( )
{
cout << “\n Number:- “ << num;
cout << “\n Count:- “ << count;
}
};
int item::count = 0;

void main( )
{
item ob1, ob2;
cout << “ \n Object Creation”;
ob1.getcount( );
ob2.getcount( );
cout << “\n Object Output”;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 13 of 25


ob1.get_data(100);

ob2.get_data(200);
ob1.getcount( );
ob2.getcount( );
getch( );
}

Static Member
Static Functions :- Static member functions are the functions that do not require an instance of the
Data Methods:
class, and are called the same way as the static data member.
Static member function can only access static data members, other static member functions and any other
functions from outside the class.
A static member function can be called even if no object of class exists and they are accessed using only the
class name and scope resolution operator.

Example:

#include <iostream.h>
#include <conio.h>
class item
{
static int count;
int num;

public:
void set_num( )
{
num = count + 1;
}
void show_num( )
{
cout << “\n Number:-“ << num;
}

Static void show_count( )


{
cout << “\n Count:- “ << count;
}
};
int item::count = 0;

void main( )
{
item ob1, ob2;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 14 of 25


ob1.set_num( );
ob2. set_num( );
item::show_count( ); // static member function called
item ob3.
ob3.set_num( );
item::show_count( );
ob1.show_num( );
ob2. show_num( );
ob3. show_num( );
getch( );
}

Inheritance: Inheritance is the capability of one class of things to inherit capabilities or properties
from another class.

The class, whose properties are inherited, is called Base Class or Super Class and the class that inherits these
properties, is called Derived Class or Sub Class.

Inheritance helps in reducing the overall code size of the program, which is an important concept in object-
oriented programming.

It is classifieds into different types, they are

• Single level inheritance


• Multi-level inheritance
• Hybrid inheritance
• Hierarchical inheritance
• Multiple inheritance

Single Level Inheritance: When a subclass inherits only from one base class, it is known as single
inheritance.

X Base Class

Y Sub Class

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 15 of 25


Syntax:
class X
{
Block of code;
----
----
};
class Y : public X
{
Block of code;
----
----
};

Multiple Inheritance: When a subclass inherits only from multiple base classes, it is known as
multiple inheritance.

X Y Base Classes

Z Sub Class

Syntax:
class X
{
Block of code;
----
----
};
class Y
{
Block of code;
----
----
};
class Z : public X, public Y
{
Block of code;
----
----
};

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 16 of 25


Hierarchical Inheritance: When multiple subclasses inherit from single base class, it is known as
hierarchical inheritance.

X Base Class

Y Z W Sub Classes

Syntax:
class X
{
Block of code;
----
----
};

class Y : public X
{
Block of code;
----
----
};

class Z : public X
{
Block of code;
----
};

class W : public X
{
Block of code;
----
};

Multilevel Inheritance: The transitive nature of inheritance is reflected by this form of inheritance.
When a subclass inherits from a class that itself inherits from another base class, it is known as multilevel
inheritance.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 17 of 25


X Base Class of Y

Y
Sub Class of X and Base Class of Z

Z
Syntax:
class X
{
Block of code;
----

----
};
class Y : class X
{
Block of code;
----
----
};
class Z : public Y
{
Block of code;
----
----
};

Hybrid Inheritance: Hybrid inheritance combines two or more forms of inheritance, i.e. when a sub
class inherits from multiple base classes and all of its base classes inherit from a single base class, this form
of inheritance is known as hybrid inheritance.

Y Z

W
Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 18 of 25
Syntax:

class X
{
Block of code;
----
----
};
class Y : public X
{
Block of code;
----
----
};
class Z : public X
{

Block of code;
----
};
class W : public Y, public Z
{
Block of code;
----
};

Need of Inheritance:

1. Capability to express the inheritance relationship which ensures the closeness with the real world
models.
2. Reusability: The advantage of reusability are faster development time, easier maintenance, and
easy to extend. Inheritance allows the addition of additional features to an existing class without
modifying it. One can derive a new class from an existing one and add new features to it.
3. One reason is transitive nature of inheritance. If a class B inherits properties of another class A, then
all subclasses of B will automatically inherit the properties of A. This property is called transitive
nature of inheritance.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 19 of 25


Examples:
Single Level Inheritance:
#include<iostream.h>
#include<conio.h>
class base
{
int a, b;
public:
void getdata( )
{
cout<< “Enter the value of a and b:-“;
cin>>a >>b;
}
void putdata( )
{
cout<<”\n The value of a is :” << a << “and b: “ << b;
}
};
class derived : public base
{
int c, d;
public:

void indata( )
{
cout<< “Enter the value of c and d:-“;
cin>>c >>d;
}
void outdata( )
{
cout<<”\n The value of a is :” << c << “and b: “ << d;
}
};

void main( )
{
derived obj;
obj.getdata( );
obj.indata( );
obj.putdata( );
obj.outdata( );
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 20 of 25


Multi Level Inheritance:
#include<iostream.h>
#include<conio.h>
class base1
{
int a, b;
public:
void getdata( )
{
cout<< “Enter the value of a and b:-“;
cin>>a >>b;
}
void putdata( )
{
cout<<”\n The value of a is :” << a << “and b: “ << b;
}
};
class base2 : public base1
{
int c, d;
public:
void indata( )
{
cout<< “Enter the value of c and d:-“;

cin>>c >>d;
}
void outdata( )
{
cout<<”\n The value of c is :” << c << “and d: “ << b;
}
};
class derived : public base2
{
int e, f;
public:
void input( )
{
cout<< “Enter the value of e and f:-“;
cin>>e >>f;
}
void output( )
{
cout<<”\n The value of e is :” << e << “and f: “ << f;
}
};

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 21 of 25


void main( )
{
derived obj;
obj.getdata( );
obj.indata( );
obj.input( );
obj.putdata( );
obj.outdata( );
obj.output( );
getch( );
}

Multiple Inheritance:
#include<iostream.h>
#include<conio.h>
class CPolygon
{
protected:
int width, height;
public:
void set_values(int a, int b)
{
width = a;
height = b;
}

};
class COutput
{
public:
void output(int i)
{
cout<< i <<endl;
}
};
class CRectangle : public CPolygon, public COutput
{
public:
int area( )
{
int r;
r = width * height;
return(r);
}
};

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 22 of 25


void main( )
{
CRectangle rect;
rect.set_values(4, 5);
rect.output(rect.area( ));
getch( );
}

Hierarchical Inheritance:
#include<iostream.h>
#include<conio.h>
class base
{
int a, b;
public:
void getdata( )
{
cout<< “Enter the value of a and b:-“;
cin>>a >>b;
}
void putdata( )
{
cout<<”\n The value of a is :” << a << “and b: “ << b;
}
};
class derived1 : public base
{

int c, d;
public:

void indata( )
{
cout<< “Enter the value of c and d:-“;
cin>>c >>d;
}
void outdata( )
{
cout<<”\n The value of c is :” << c << “and d: “ << b;
}
};
class derived2 : public base
{
int e, f;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 23 of 25


public:
void input( )
{
cout<< “Enter the value of e and f:-“;
cin>>e >>f;
}
void output( )
{
cout<<”\n The value of e is :” << e << “and f: “ << f;
}
};

void main( )
{
derived1 obj1;
derived2.obj2;
obj1.getdata( );
obj1.indata( );
obj2.getdata( );
obj2.input( );
obj1.putdata( );
obj1.outdata( );
obj2.putdata( );
obj2.output( );
getch( );
}

Hybrid Inheritance:
#include<iostream.h>
#include<conio.h>
class base

{
int a, b;
public:
void getdata( )
{
cout<< “Enter the value of a and b:-“;
cin>>a >>b;
}
void putdata( )
{
cout<<”\n The value of a is :” << a << “and b: “ << b;
}
};
class derived1 : public base

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 24 of 25


{
int c, d;
public:
void indata( )
{
cout<< “Enter the value of c and d:-“;
cin>>c >>d;
}
void outdata( )
{
cout<<”\n The value of c is :” << c << “and d: “ << b;
}
};
class derived2 : public base
{
int e, f;
public:
void input( )
{
cout<< “Enter the value of e and f:-“;
cin>>e >>f;
}
void output( )
{
cout<<”\n The value of e is :” << e << “and f: “ << f;
}
};

void main( )
{
derived1 obj1;
derived2.obj2;
obj1.getdata( );
obj1.indata( );
obj2.getdata( );

obj2.input( );
obj1.putdata( );
obj1.outdata( );
obj2.putdata( );
obj2.output( );
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 25 of 25

You might also like