[go: up one dir, main page]

0% found this document useful (0 votes)
25 views36 pages

Units 2

Uploaded by

bishirvv5
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)
25 views36 pages

Units 2

Uploaded by

bishirvv5
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/ 36

1.

0 Need of Object Oriented Programming


 Developments in software technology continue to be dynamic. New tools
and techniques are announced in quick succession.
 This has forced the software engineers and industry to continuously look for
new approaches to software design and development, and they are becoming
more and more critical in view of the increasing complexity of software
system as well as the highly competitive nature of the industry.
 This rapid advance appears to have created a situation of crises within the
industry.
The following issues needs to be solved:
 To represent real life entities of problems in system design.
 To design system with open interface.
 To ensure reusability and extensibility of modules.
 To develop modules that is tolerant to any changes in future
 To improve software productivity and decrease cost.
 To improve the quality of the software.
 To manage time schedule.
 To industrialize the software development process.
To overcome these problems and major motivation factor in the invention of object
oriented approach is to remove some of the flows encountered in the procedure
oriented approach.

1.1 Object Oriented Programming


Object Oriented Programming is the most recent concept among programming model.
The motivating factor in the invention of object oriented approach is to remove
some of the flows encountered in the procedural approach. OOPS treats data as a
critical element in the program development and does not allow it to flow freely
around the system. It binds data more closely to the functions that operate on it, and
protects it from accidental modification from outside functions.
Some of the striking features of Object Oriented Programming are:
 Importance on data rather than procedure.
 Programs are divided into what are known as objects.
Data structures are designed as such that they characterize the objects.
Introduction to OOPs
 Functions that operate on the data of an object are tied together in the data
structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follow bottom-up approach in program design.

5
OBJECT ORIENTED PROGRAMMING

1.2 Comparison of Procedural and Object Oriented Approach


There are two different approaches to write a program, i.e., Procedure Oriented
Programming and Object Oriented Programming. Basic aim of these methods is
nothing but to make programming efficient. We can write the program using any of
the way but there are notable differences between both approaches.

Sr. Procedure Oriented Programming Object Oriented Programming


No
POP is divided into small parts In OOP, program is divided into
called as functions parts called objects

In POP, Importance is not given to In OOP, Importance is given to


data but to functions as well as the data rather than procedures or
sequence of actions to be done. functions because it works as a
real world.
POP follows top-down approach. OOP follows bottom-up approach.

POP does not have any access OOP has access specifiers named
specifier. Public, Private, Protected, etc.

In POP, data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other
through member functions.
To add new data and function in OOP provides an easy way to add
POP is not so easy. new data and function.
In POP, most function uses global In OOP, data cannot move easily
data for sharing that can be accessed from function to function, it can be
freely from function to function in kept public or private so we can
the system. control the access of data.
POP does not have any proper way OOP provides data hiding so
for hiding data so it is less secure. provides more security.
In POP, overloading is not possible. In OOP, overloading is possible in
the form of Function Overloading
and Operator Overloading.
Example of POP are: C, VB, FOR- Example of OOP are: C++, JAVA,
TRAN, Pascal. VB.NET, C#.NET.

6
Chapter 1 : Objects Methodology

1.3 Benefits of OOP


1) As OOP is closer to the real world phenomena, hence, it is easier to map real
world problems onto a solution in OOP.
2) The objects in OOP have the state and behaviour that is similar to the real
world objects.
3) It is more suitable for large projects.
4) The projects executed using OOP techniques are more reliable.
5) It provides the bases for increased testability (automated testing) and hence
higher quality.
6) Abstraction techniques are used to hide the unnecessary details and focus is
only on the relevant part of the problem and solution.
7) Encapsulation helps in concentrating the structure as well as the behaviour of
various objects in OOP in a single enclosure.
8) The enclosure is also used to hide the information and to allow strictly controlled
access to the structure as well as the behaviour of the objects.
9) OOP divides the problems into collection of objects to provide services for
solving a particular problem.
10) Object oriented systems are easier to upgrade/modify.
11) The concepts like inheritance and polymorphism provide the extensibility of
the OOP languages.
12) The concepts of OOP also enhance the reusability of the code written.
13) Software complexity can be better managed.
14) The use of the concept of message passing for communication among the objects
makes the interface description with external system much simpler.
15) The maintainability of the programs or the software is increased manifold. If
designed correctly, any tier of the application can be replaced by another
provided the replaced tier implements the correct interface(s). The application
will still work properly.

1.4 Advantages of OOPs


1. Code reusability in terms of inheritance.
2. Object-oriented system can be easily upgraded from one platform to another.
3. Complex projects can be easily divided into small code functions.
4. The principle of abstraction and encapsulation enables a programmer to build
secure programs.
5. Software complexity decreases.
6. Principle of data hiding helps programmer to design and develop safe programs.
7. Rapid development of software can be done is short span of time.
8. More than one instance of same class can exist together without any interference.

7
OBJECT ORIENTED PROGRAMMING

1.5 Object Oriented Languages

Some of the most popular Object-oriented Programming languages are :


a)C++
b)Ruby
c)Java.
d)Delphi
e) smalltalk
f) Charm++
g)Eiffle.
h)Simula.

1.6 Applications of OOPS

Object concept helps to translate our thoughts to a program. It provides a way of


solving a problem in the same way as a human being perceives a real world problem
and finds out the solution. It is possible to construct large reusable components
using object-oriented techniques. Development of reusable components is rapidly
growing in commercial software industries. If there is complexity in software
development, object-oriented programming is the best
paradigm to solve the problem. The following areas make the use of OOP:
1. Image Processing
2. Pattern Recognition
3. Computer Assisted Concurrent Engineering
4. Computer Aided Design and Manufacturing
5. Computer Aided Teaching
6. Intelligent Systems
7. Database Management Systems
8. Web-based Applications
9. Distributed Computing and Applications
10. Component-based Applications
11. Business Process Re-engineering
12. Enterprise Resource Planning
13. Data security and management
14. Mobile Computing
15. Data Warehouse and Data Mining
16. Parallel Computing

8
Chapter 1 : Objects Methodology

1.7 Questions
Q1. Why does hardware not provide flexibility of operations to the user ?
Q2. How is a program related to software?
Q3. What is the signature of a method?
Q4. Differentiate between information hiding and encapsulation.
Q5. What is the difference between object-oriented and object-based programming
languages?
Q6. What is the need of Object Oriented Programming ?
Q7. Differentiate Procedure Oriented Programming & Object Oriented
Programming
Q8. List and explain benefits of OOP .
Q9. List and explain application of OOPS
PRINCIPLES OF OOPS
2.0 Object Oriented Programming Paradigm

 Simula was the first programming language developed in the mid-1960s to


support the object-oriented programming paradigm followed by Smalltalk
in the mid-1970s that is known to be the first ‘pure’ object-oriented language.
 Eiffel, Java, C++, Object Pascal, Visual Basic, C# etc are the other OOP
languages that came into existence later on, all having different complexities
of syntax and dynamic semantics.
 The main motive of the developers of programming languages over the years
has always been to create such programming languages that are close to
human (i.e. natural) languages.
 The way we perceive and interact with the things in our day-to-day lives, the
representation of programming constructs should closely match the same.
Hence came into existence the concept of ‘objects’ and ‘object-oriented
programming paradigm’.
 Every object has certain defining properties which distinguish it not only
from different types of other objects but from the similar types of objects
too.
 Every object has certain functions associated with it and all similar types of
objects are supposed to support these. Although, Some of these functions
can be the same as associated with different types of objects.
Chapter 2 : Principles of OOPS

 Example with Explanation : In case of a ball pen, one of the functions


associated with each type of ball pen object, is to write and another associated
function is the provision to hold it in hands conveniently. All the ball pen
objects support both these functions. Incidentally, all the tooth brush objects
also support the function of holding them in the hands conveniently but, in
addition, support other functions like brushing the teeth too.
 This concept of objects borrowed from the real world has been the basis of
the object-oriented programming (OOP) paradigm and this paradigm is a
direct consequence of an effort to have a programming language closely
matching the human behaviour.
 This OOP paradigm is all about creating program(s) dealing with objects
where these objects interact with one another to achieve the overall objectives
of the program. Every object in the programs has certain defining properties
called attributes (or instance variables) possessing supporting values for each
of the attributes and some associated functions (normally called methods or
operations). As in the real world objects, no two objects in a program can
have the same values of all the attributes.
 At times, instead of dealing with individual objects, it is convenient to talk
collectively about a group of similar objects where all the objects of this
group will have the same set of attributes and methods.
 In the object-oriented programming paradigm parlance, this collection of
objects corresponding to a particular group is known as a class.
 All programs under this paradigm contain a description of the structure
(corresponding to attributes) and behaviour (corresponding to methods) of
so called classes.
 In a program, various objects are created from these classes. The process of
creation of an object from a class is called ‘instantiation’ and the object created
is known as an instance of the class.
 Every object created will have a ‘state’ associated with the description of the
structure in the class from which it has been instantiated.
 The state of an object is defined by the set of values assigned to its
corresponding attributes (and stored in the memory) of the object.
 A class is defined to be a template or a prototype so that a collection of
attributes and methods can be described within it and this definition can be
used for creating different objects within a program.
 It is this concept of encapsulating the data and methods within the objects
that provides the programmers with flexibility within the OOP paradigm
because an object can be extended or modified without making changes to
its external interface or other classes/objects in the program.
 Various classes may exhibit features like inheritance and polymorphism of
methods.

11
OBJECT ORIENTED PROGRAMMING

2.1 Characteristics of OOPS / Concepts of OOPS

Characteristics of OOPs are :


 Object
 Classes
 Polymorphism
 Inheritance
 Reusability
 Data abstraction and encapsulation
 Dynamic Binding
 Message Passing

2.1.0 Class
 A group of objects that share common properties for data part and some
program part are collectively called as class.
 In C ++ a class is a new data type that contains member variables and member
functions that operate on the variables.
 The most remarkable feature of C + + is a class. The class binds together
data and methods which work on data. The class is an abstract data type
(ADI) so creation of class simply creates a template.
 The class is a keyword.
 The general syntax of creating a class in C++ is given below:

12
Chapter 2 : Principles of OOPS

class class name


{
public :
data & function;
private :
data & function;
protected :
data & function;
};

Following this keyword class, class_name represents name of the class. The class
name must obey rules of writing identifier as class_name is nothing but an identifier.
The class is opened by opening brace} and closed by closing brace}. The class
definition/declaration must end with semicolon. Inside the class we define the data
members and member functions. They may be defined either public, private or jn
protected mode.
There are three different types of mode :
1. public
2. private
3. protected.

2.1.1 Object
 Objects are the basic run time entities in an Object Oriented System.
 They may represent a person, a bank account, a table of data or any item
that the program has to handle.
 They may also represent user-defined data such as vector, time, and lists.
 When a program is executed, the objects interact by sending messages to
one another.
 Creating objects is similar to declaring variables.

Syntax:
<Class Name> <Object Name>;

For Example:
Student s1;
Where Student is a class name and s1 is its object.

13
OBJECT ORIENTED PROGRAMMING

2.1.2 Polymorphism
 Poly means many. Morphism means forms.
 Polymorphism feature enables classes to provide different implementation
of methods having the same name.
 There are two types of polymorphism:
1. Compile time (Overloading)
2. Run time (Overriding)

2.1.3 Inheritance
 Inheritance is the process by which objects of one class acquire the properties
of objects of another class.
 It supports the concept of hierarchical classification.
 The existing class is called as base class and a new class which is created on
the basis of base class is called as derived class.
 There are 5 different types of inheritance, i.e.:
 Single level
 Multilevel
 Multiple
 Hierarchical
 Hybrid

2.1.4 Reusability
 The concept of inheritance provides an important feature to the object-oriented
languagereusability.
 A programmer can take an existing class and, without modifying it, and
additional features and capabilities to it.
 This is done by deriving a new class from an existing class.

2.1.5 Data Abstraction and Encapsulation


 The wrapping up of data and functions into a single unit is known as
encapsulation.
 Data encapsulation is the most striking feature of a class.
 Abstraction refers to the act of representing essential features without
including the background details or explanations.
 Encapsulation is the hiding of information in order to ensure that data
structures and operators are used as intended and to make the usage model
more obvious to the developer.

14
Chapter 2 : Principles of OOPS

 C++ provides the ability to define classes and functions as its primary
encapsulation mechanisms.

2.1.6 Dynamic Binding


 Binding means linking.
 It is linking of function definition to a function call.
1. If linking of function call to function definition i.e., a place where
control has to be transferred is done at compile time, it is known as
static binding.
2. When linking is delayed till run time or done during the execution of
the program then this type of linking is known as dynamic binding.
Which function will be called in response to a function call is find
out when program executes.

2.1.7 Message Passing


 In C++ objects communicate each other by passing messages to each other.
 A message contains the name of the member function and arguments to pass.
In message passing shown below :
object. method (parameters);

 Message passing here means object calling the method and passing
parameters.
 Message passing is nothing but the calling the method of the class and sending
parameters.
 The method is turn executes in response to a message.
OBJECT ORIENTED PROGRAMMING

2.2 Summary
 The programs are the means through which we can make the computers
produce the useful desired outputs.
 Out of a variety of programming paradigms being used by practitioners as
well as the researchers, the structured and the object-oriented programming
paradigm and corresponding structured and object-oriented programming
have been in focus for quite some time now.
 In this unit, you studied that the structured programming languages initially
helped in coping with the inherent complexity of the softwares of those times
but later on, were found wanting in the handing the same as far as the software
of present days are concerned.
 you were introduced to the concepts of object-oriented programming
paradigm and it was illustrated as to how this paradigm is closer to natural
human thinking.
 It was followed by the illustrations of some more concepts of object-oriented
programming like classes, objects, message passing, interface, associations,
inheritance and polymorphism.
 In the end, you saw what the various benefits of OOPs are and how can these
help in producing good quality software.
CLASSES AND OBJECTS

Defining Class and Declaring Objects

A class is defined in C++ using keyword class followed by the name of class. The
body of class is defined inside the curly brackets and terminated by a semicolon at
the end.
OBJECT ORIENTED PROGRAMMING

Declaring Objects

When a class is defined, only the specification for the object is defined; no memory
or storage is allocated. To use the data and access functions defined in the class, you
need to create objects.

Syntax:

ClassName ObjectName;

Accessing data members and member functions

The data members and member functions of class can be accessed using the dot(‘.’)
operator with the object. For example if the name of object is obj and you want to
access the member function with the name printName() then you will have to
write obj.printName() .

Accessing Data Members

The public data members are also accessed in the same way given however the
private data members are not allowed to be accessed directly by the object. Accessing
a data member depends solely on the access control of that data member.
This access control is given by Access modifiers in C++. There are three access
modifiers : public, private and protected.

Access-control specifiers Accessible to

Own class members Objects of a class


private yes no
protected yes no
public yes yes

A class can use all of three visibility/accessibility labels as illustrated below:

Class A
{
private:
int x;
void fun1()
{
// This function can refer to data members x, y, z and functions fun1(), fun2()
and fun3()

40
Chapter 3 : Classes and Objects

}
protected:
int y;
void fun2()
{
//This function can also refer to data members x, y, z and functions fun1(),
fun2() and fun3()
}
public :
int z;
void fun3()
{
//This function can also refer to data members x, y, z and functions fun1(),
fun2() and fun3()
}
};
Now, consider the statements
A obja; //obja is an object of class A
int b; // b is an integer variable

The above statements define an object obja and an integer variable b. The accessibility of
members of the class A is illustrated through the obja as follows:
1. Accessing private members of the class A:
b=obja.x; //Won t Work: object can not access private data member „x obja.fun1();
//Won t Work: object can not access private member function fun1() Both the statements
are illegal because the private members of the class are notaccessible.

2. Accessing protected members of the class A:


b=obja.y; // Won t Work: object can not access protected data member „y obja.fun2(); //
Won t Work: object can not access member function fun2() Both the statements are also
illegal because the protected members of the classare not accessible.

3. Accessing public members of the class A: b=obja.c;


//OK
obja.fun3(); //OK
Both the statements are valid because the public members of the class are
accessible.

41
OPERATORS IN C++ :

C++ has a rich set of operators. All C operators are valid in C++ also. In addition. C++
introduces some new operators.

<< insertion operator

>> extraction operator

:: scope resolution operator

: :* pointer to member declarator

* pointer to member operator

.* pointer to member operator

Delete memory release operator

Endl line feed operator

New memory allocation operator

Setw field width operator

SCOPE RESOLUTION OPERATOR:

Like C,C++ is also a block-structured language. Block -structured language. Blocks and
scopes can be used in constructing programs. We know same variables can be declared in different
blocks because the variables declared in blocks are local to that function.
Blocks in C++ are often nested.
Example:

{
Int x =10;

Int x=1; Block2


--------------- Block1

}
Block2 contained in block l .Note that declaration in an inner block hides a declaration of the
same variable in an outer block and therefore each declaration of x causes it to refer to a different data object .
With in the inner block the variable x will refer to the data object declared there in.
In C,the global version of a variable can't be accessed from with in the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution operator .This can be
used to uncover a hidden variable.

Syntax: : : variable –name;

Example:
#include <iostrcam.h>
int m=10;
main()
{
int m=20;
{
int k=m;
int m=30;
cout<<”we are in inner block”;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
cout<<”\n we are in outer block \n”;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}

Memory Management Operator


C uses malloc and calloc functions to allocate memory dynamically at run time . Similarly it uses the functions
Free( ) to free dynamically allocated memory. We use dynamic allocation techniques when it is not known in
advance how much of memory space as needed .

C++ also support those functions it also defines two unary operators new and delete that
perform the task of allocating and freeing the memory in a better and easier way.

The new operator can be used to create objects of any type. Syntax: pointer-

variable =new datatype;

Example:
p=new int; q=new int;

Where p is a pointer of type int and q is a pointer of type float.

int *p=new int;

float *p=newfloat;

Subsequently, the statements

*p=25;
*q=7.5;
Assign 25 to the newly created int object and 7.5 to the float object.We can also initialize the memory
using the new operator.

Syntax:
int *p=ne\v int(25);
float *q =new float(7.5);
new can be used to create a memory space for any data type including user defined such as
arrays,structures,and classes .The general form for a one-dimensional array is:

pointer-variable =new data types [size];

creates a memory space for an array of 10 integers.

If a data object is no longer needed, it is destroyed to release the memory space for reuse.

Syntax: delete pointer-variable;

Example:
delete p;
delete q;

If we want to free a dynamically allocated array ,we must use the following
form of delete.

delete [size] pointer-variable;


or

delete [ ] pointer variable;

MANIPULATERS:

Manipulators are operator that are used to format the data display. The most commonly manipulators are
endl and setw.
The endl manipulator, when used in an output statement, causes a line feed to be insert.(just like \n)

Example:
cout<<”m=”<<m<<endl;
cout<<”n=”<<n<<endl;
cout<<”p=”<<p<<endl;
If we assume the values of the variables as 2597,14 and 175 respectively
m=2597; n=14;
p=175
It was want to print all nos in right justified way use setw which specify a common field width
for all the nos.

Example: cout<<setw(5)<<sum<<endl;
cout<<setw(10)<<”basic”<<setw(10<<basic<<endl;
Cout<<setw(10)<<”allowance”<<setw(10<<allowance<<endl;
cout<<setw(10)<<”total=”<<setw(10)<<total;
Member Functions in Classes

A member function performs an operation required by the class. It is the actual interface to initiate an
action of an object belonging to a class. It may be used to read, manipulate, or display the data member.
The data member of a class must be declared within the body of the class, while the member functions of a
class can bedefined in two places:
⬧ Inside class definition
⬧ Outside class definition
The syntax of a member function definition changes depending on whether it is defined inside or outside
the class declaration/definition. However, irrespective of the location of their definition, the member
function must perform the same operation. Thus, the code inside the function body would be identical in
both the cases. The compiler treats these two definitions in a different manner. Let us see, how we can
define the member function inside the class definition.

The syntax for specifying a member function declaration is similar to a normal function definition except
that is enclosed within the body of a class. For example, we could define the class as follows:

class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<“\n Minimum value is =”<<min<<endl;
}
};

if you look at the above declaration of class number you can observe that the member function get_data() and
maiximun() are declared, but they are not defined. The only member function which is defined in the class
body is minimum(). When a function is defined inside a class, it is treated as a inline function. Thus,
member function minimum is a inline function. Generally, only small functions are defined inside theclass.
Now let us see how we can define the function outside the class body. Member functions
that are declared inside a class have to be defined outside the class. Their definition is very
much like the normal function. Can you tell how does a compiler know to which class
outside defined function belong? Yes, there should be a mechanism of binding the functions
to the class to which they belong. This is done by the scope resolution operator (::). It acts as
an identity-label. This label tells the compiler which class the function belongs to. The
common syntax for member function definition outside the class is as follows:

return_type class_name :: function_name(argument declaration)


{
functionbody
}
The scope resolution :: tells the compiler that the function_name belongs to the
class class_name. Let us again consider the class Number.
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration.
.
.
};
void Number :: get_data(void)
{
cout<< “\n Enter the value of fist number(x):”<<endl;
cin>>x;
cout<< “\n Enter the value of second number(y):”<<endl;
cin>>y;
cout<< “\n Enter the value of third number(z):”<<endl;
cin>>z;

}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<“\n Maximun value is =”<<max<<endl;
}
if you look at the above declaration of class Number, you can easily see that the member function
get_data() and maiximun() are declared in the class. Thus, it is necessary that you have to define this
function. You can also observe in the above snapshot of C++ program identity label (::) which are used in
void Number :: get_data(void) and void Number ::maximum(void) tell the compiler the
functionget_data() and maximum() belong to the class Number
let us see the complete C++ program to find out the minimum and maximum of three given integer
numbers

#include<iostream.h>
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<“\n Minimum value is =”<<min<<endl;
}
};
void Number :: get_data(void)
{
cout<< “\n Enter the value of fist number(x):”<<endl;
cin>>x;
cout<< “\n Enter the value of second number(y):”<<endl;
cin>>y;
cout<< “\n Enter the value of third number(z):”<<endl;
cin>>z;
}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<“\n Maximun value is =”<<max<<endl;
}
void main()
{
Number num;
num.get_data();
num.minimum();
num.maximum();
}

output:
Enter the value of the first number (x):
10
Enter the value of the second number (y):
20
Enter the value of the third number (z):
5
Minimum value is=5
Maximum value is=20
CONSTRUCTORS AND DESTRUCTORS
Constructor is a special member function whose name is same as the name of its class in which it is
declared and defined. The purpose of the constructor is to initialize the objects of the class. The constructor
is called so because it is used to construct the objects of the class.
Example of constructor and later illustrate its various features :

#include < iostream.h >


#include < conio.h >
class demo
{
public:
demo()
{
cout< <“Hello from constructor \n”;
}
};
void main()
}
clrscr( );
demo d;
getch( );

OUTPUT :

Hello from constructor

4.1 Features of the Constructor

1. The constructors are always declared in the public section. If declared in the private
section then objects are can only be created inside the member functions but serve no
purpose.
2. They are invoked automatically when objects of the class are created. The
declaration demo d;creates an object d which automatically calls the constructor of
the class and prints Hello from constructor.
3. They do not have any return type not even void so they cannot return any value.
4. Constructors cannot be inherited, but they can be called from the constructorsof derived
class.
5. Constructors are used to construct the object of the class.
6. The constructor with no argument is known as default constructor of theclass. The
default constructor for the class demo will be demo : demo( )
7. Constructors which take arguments like a function takes are known as
parameterized constructor.
8. There is no limit of the number of constructors declared in a class but theyall must
conform to rules of function overloading.
9. Constructor can have default arguments.
10. Addresses of constructors cannot be taken.
11. Constructors cannot be virtual.
12. Constructor make implicit calls to operators new and delete in case memoryallocation and de-
allocation is to be performed

TYPES OF CONSTRUCTURS

i) Default Constructors

A constructor that accept no parameter is called the default


constructor. The default constructor for class A is A :: A( ).
If no such constructor isdefined, then the compiler supplies a default constructor .
Therefore a statement such as :-
A a ;//invokes the default constructor of the compiler of the compiler to
create the object "a" ;
Invokes the default constructor of the compiler to create the object a.The
constructor functions have some characteristics:-
 They should be declared in the public section .
 They are invoked automatically when the objects are created.
 They don't have return types, not even void and therefore
they cannot return values.
 They cannot be inherited , though a derived class can call
the base class constructor .
 Like other C++ function , they can have default arguments,
 Constructor can't be virtual.
 An object with a constructor can't be used as a member of
union.

Example of default constructor:

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

class abc
{
private:
char nm[];
public:
abc ( )
{
cout<<”enter your name:”;
cin>>nm;
}
void display( )

{
cout<<nm;
}

};

int main( )
{
clrscr( );
abc d;
d.display( );
getch( );
return(0);
}

ii) PARAMETERIZED CONSTRUCTOR:-


The constructors that can take arguments are called parameterized
constructors. Using parameterized constructor we can initialize the various data elements of different
objects with different values when they are created.
Example:-
class integer
{
int m,n;
public:
integer( int x, int y);

};
integer:: integer (int x, int y) m=x;n=y;
{

}
the argument can be passed to the constructor by calling the constructor
implicitly.
integer int 1 = integer(0,100); // explicit call
integer int 1(0,100); //implicite call
CLASS WITH CONSTRUCTOR:-

#include<iostream.h>
class integer
{
int m,n;
public:
integer(int,int);
void display(void)

{
cout<<”m=:”<<m ;
cout<<”n=”<<n;
}
};
integer :: integer( int x,int y) // constructor defined
{
m=x;
n=y;
}
int main( )
{

integer int 1(0, 100); // implicit callinteger


int2=integer(25,75);
cout<<” \nobjectl “<<endl; int1.display( );
cout<<” \n object2 “<<endl;int2.display( );
}

output:
object 1m=0 n=100
object2 m=25 n=75

iii) COPY CONSTRUCTOR:


A copy constructor is used to declare and initialize an object from another object.
Example:-
the statement
integer 12(11);
would define the object 12 and at the same time initialize it to the values of 11.
Another form of this statement is : integer 12=11;
The process of initialization through a copy constructor is known as copy initialization.
Example:-
#incliide<iostream.h>
class code
{
int id;
public
code ( ) { } //constructor
code (int a) { id=a; } //constructor
code(code &x)
{
Id=x.id;
}
void display( )
{
cout<<id;
}
};
int main( )
{
code A(100);
code B(A);
code C=A;
code D;
D=A;
cout<<” \n id of A :”; A.display( );
cout<<” \nid of B :”; B.display( );
cout<<” \n id of C:”; C.display( );
cout<<” \n id of D:”; D.display( );
}

output :-
id of A:100
id of B:100
id of C:100
id of D:100

iv) 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, thus resulting in the saving of memory.
Allocate of memory to objects at the time of their construction is known as dynamic
constructors of objects. The memory is allocated with the help of new operator.
Example:-
#include<iostream.h>
#include<string.h>
class string
{
char *name;

int length;
public:
string ( )

{
length=0;
name= new char [length+1]; /* one extra for \0 */
}
string( char *s) //constructor 2
{
length=strlen(s);
name=new char [length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<endl;
}
void join(string &a .string &b)
{
length=a. length +b . length;
delete name;
name=new char[length+l]; /* dynamic allocation */
strcpy(name,a.name);
strcat(name,b.name);
}
};
int main( )
{
char * first = “Joseph” ;
string name1(first),name2(“louis”),naine3( “LaGrange”),sl,s2;
sl.join(name1,name2);
s2.join(s1,name3);
namel.display( );
name2.display( );
name3.display( );
s1.display( );
s2.display( );
}
output :-
Joseph
Louis
language
Joseph Louis
Joseph Louis Language
4.1 Destructor

A destructor is a member function of the class whose name is same as the name of the class
but the preceded with tilde sign (~). The purpose of destructor is to destroy the object when it is
no longer needed or goes out of scope. As a very small exampleof destructor see the program
given below :

#include <iostream.h>
#include <conio.h>
class demo
{
public :
demo( )
{
cout<<“Constructor called\n”;
}
~demo( )
{
cout<<“Destructor called”<<endl;
}
};
void main( )
{
clrscr( );
demo d;
getch( );
}

OUTPUT :

Constructor called
Destructor called

4.2 Features of Destructor

1. The name is same as of class but proceeded with a ~ sign.


2. Destructor is automatically called as soon as an object goes out of scope.
3. Destructor is used to destroy the objects.
4. Once a destructor is called for a object, the object will no longer be available for the
future reference.
5. Destructor can be used for housekeeping work such as closing the file, de-allocating
the dynamically allocated memory etc. Closing a file in destructor
is a good idea as user might forget to close the file associated with object. But as the object goes out of scope
destructor will be called and all code written in destructor executes which will always result in closing the file
andno data loss may be there. When new is used for allocation of memory in the constructor we must always use
delete in the destructor to be allocate the memory.
6. Similar to constructor there is no return type for destructor and that’s whythey cannot return any
value.
7. There is no explicit or implicit category for a destructor. They are alwayscalled implicitly by the
compiler.
8. Destructor can never take any arguments.
9. Destructor can be virtual.

FRIENDLY FUNCTIONS:-
We know private members can not be accessed from outside the class. That is a non -
member function can't have an access to the private data of a class. However there could be a case
where two classes manager and scientist, have been defined we should like to use a function income-
tax to operate on the objects of both these classes.
In such situations, c++ allows the common function lo be made friendly with both the classes , there
by following the function to have access to the private data of these classes .Such a function need not
be a member of any of these classes.
To make an outside function "friendly" to a class, we have to simply declare this function as a friend
of the classes as shown below :

class ABC
{

public:

friend void xyz(void);


};

The function declaration should be preceded by the keyword friend , The function is defined else
where in the program like a normal C ++ function . The function definition does not use their the
keyword friend or the scope operator :: . The functions that are declared with the keyword friend are
known as friend functions. A function can be declared as a friend in any no of classes. A friend
function, as though not a member function , has full access rights to the private members of the class.

A friend function processes certain special characteristics:


a. It is not in the scope of the class to which it has been declared as friend.
b. Since it is not in the scope of the class, it cannot be called using the object of that
class. It can be invoked like a member function without the help of any object.
c. Unlike member functions.

Example:

#include<iostream.h>
class sample
{
int a;
int b;
public:
void setvalue( ) { a=25;b=40;}
friend float mean( sample s);
}
float mean (sample s)
{
return (float(s.a+s.b)/2.0);
}
int main ( )
{
sample x;
x . setvalue( );
cout<<”mean value=”<<mean(x)<<endl;
return(0);

output:
mean value : 32.5

A function friendly to two classes


#include<iostream.h>
class abc;
class xyz
{
int x;
public:
void setvalue(int x) { x-= I; }
friend void max (xyz,abc);
};
class abc
{
int a;
public:
void setvalue( int i) {a=i; }
friend void max(xyz,abc);
};

void max( xyz m, abc n)


{
if(m . x >= n.a)
cout<<m.x;
else
cout<< n.a;
}
int main( )
{
abc j;
j.
setval
ue(
10);
xyz s;
s.setv
alue(2
0);
max(
s , j );
return
(0);
}

this Pointer

Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.
Let us try the following example to understand the concept of this pointer “

#include <iostream>

using namespace std;

class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<“Constructor called.” << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(5.6, 1.2, 5.1); // Declare box1
Box Box2(2.5, 4.1, 6.1); // Declare box2

if(Box1.compare(Box2)) {
cout << “Box2 is smaller than Box1” <<endl;
} else {
cout << “Box2 is equal to or larger than Box1” <<endl;
}

return 0;
}

Output :
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1

You might also like