Vous êtes sur la page 1sur 25

Object Oriented Programming With C++

[1].Different Between Procedure oriented programming and Object


Oriented Programing:
[1]. In POP Main program is divided into small parts depending on the functions.
In OOPS Main program is divided into small object depending on the problem.
[2]. In POP There is no perfect way for data hiding.
In OOPS Data hiding possible in OOP which prevent illegal access of function from
outside of it. This is one of the best advantages of OOP also.
[3]. In POP Top down process is followed for program design.
In OOPS Bottom up process is followed for program design.
[4]. In POP Importance is given to the sequence of things to be done.
In OOPS Importance is given to the data.
[5]. In POP Mostly functions share global data i.e data move freely around the system
from function to function.
In OOPS mostly the data is private.
[6]. In POP No access specifier.
In OOPS There are public, private, protected specifier.
[7].

In POP Operator cannot be overloaded.


In OOPS Operator can be overloaded

[8]. In POP C, Pascal, FORTRAN.


In OOPS C++ , Java.

[2].Different between C and C++


[1]. C follows the procedural programming paradigm while C++ is a multi-paradigm
language (procedural as well as object oriented)
In case of C, importance is given to the steps or procedure of the program while C+
+ focuses on the data rather than the process. Also, it is easier to implement/edit
the code in case of C++ for the same reason.
[2].

In case of C, the data is not secured while the data is secured(hidden) in C++
This difference is due to specific OOP features like Data Hiding which are not
present in C.

[3].

C is a low-level language while C++ is a middle-level language (Relatively,


Please see the discussion at the end of the post)

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 1

Object Oriented Programming With C++


C is regarded as a low-level language (difficult interpretation & less user friendly)
while C++ has features of both low-level(concentration on whats going on in the
machine hardware) & high-level languages(concentration on the program itself) &
hence is regarded as a middle-level language.
[4].

C uses the top-down approach while C++ uses the bottom-up approach

In case of C, the program is formulated step by step, each step is processed into
detail while in C++, the base elements are first formulated which then are linked
together to give rise to larger systems.
[5].

C is function-driven while C++ is object-driven


Functions are the building blocks of a C program while objects are building blocks of
a C++ program.

[6].

C++ supports function overloading while C does not


Overloading means two functions having the same name in the same program. This
can be done only in C++ with the help of Polymorphism (an OOP feature).

[7].

We can use functions inside structures in C++ but not in C.


In case of C++, functions can be used inside a structure while structures cannot
contain functions in C.

[8].

The NAMESPACE feature in C++ is absent in case of C


C++ uses NAMESPACE which avoid name collisions. For instance, two students
enrolled in the same university cannot have the same roll number while two
students in different universities might have the same roll number. The universities
are two different namespace & hence contain the same roll number(identifier) but
the same university(one namespace) cannot have two students with the same roll
number(identifier)

[9].

The standard input & output functions differ in the two languages
C uses scanf & printf while C++ uses cin>> & cout<< as their respective input &
output functions

[10]. C++ allows the use of reference variables while C does not
Reference variables allow two variable names to point to the same memory
location. We cannot use these variables in C programming.
[11]. C++ supports Exception Handling while C does not.
C does not support it "formally" but it can always be implemented by other
methods. Though you don't have the framework to throw & catch exceptions as in
C++.
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 2

Object Oriented Programming With C++

[3].Basic Concept of Object Oriented programming


Class ::
A class is the implementation of an abstract data type (ADT). It defines attributes and
methods which implement the data structure and operations of the ADT, respectively.
Instances of c lasses are called objects . Consequently, classes define prop erties and
behaviour of sets of objects.
Class is a collection of member data and member functions. objects contain data and code to
manipulate that data. The entire set of data and code of an object can be made a user-defined
data type with the help of a class. In fact, objects are variables of type class. Once a class has
-been defined, we can create any number of objects belonging to that class. Each object is
associated with the data of type class with which they are created: A class is thus a collection of
objects of similar type. For example, mango, apple and orange are members of the class fruit:
Classes are user-defined data types and behave like the built-in types of a programming language.
For example, the syntax used to create an object is no different than the syntax used to create an
integer object in C. If fruit has been defined as a class, then the statement fruit mango; will create
an object mango belonging to the class fruit.

Object::
An object is an instance of a class. It can be uniquely identified by its name and
it
defines a state which is represented by the values of its attributes at a particular time.
The state of the object changes according to the methods which are applied to it. We refer
to these possible sequence of state changes as the behaviour of the object.

Behaviour::
The behaviour of an object is defined by the set of methods which can be applied on it.

Message::
A message is a request to an object to invoke one of its methods. A message therefore
contains the name of the method and the arguments of the method. Consequently,
invocation of a method is just a reaction caused by receipt of a message. This is only
possible, if the method is actually known to the object.

Method::
A metho d is associated with a class. An object invokes methods as a reaction to receipt
of a message.

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 3

Object Oriented Programming With C++

Data Abstraction:

Abstraction refers to the act of representing essential features without including the
background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and functions to operate on these
attributes.
They encapsulate all the essential properties of the objects that are to be created.
Since the classes use the concept of data abstraction, they are known as Abstract
Data Types (ADT).

Encapsulation:

The wrapping up of data and functions into a single unit (called class) is known as encapsulation.
The data is not accessible to the outside world and only those functions which are wrapped in the class
can access it.
These functions provide the interface between the object's data and the program.
This insulation of the data from direct access by the program is called data hiding.

Features and Advantages of the concept of Encapsulation:


1) Makes Maintenance of Application Easier:
Complex and critical applications are difficult to maintain. The cost associated with
maintaining the application is higher than that of developing the application properly. To
resolve this maintenance difficulty, the object-oriented programming language C++
created the concept of encapsulation which bundles data and related functions together
as a unit called class, thus making maintenance much easier on the class level.
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 4

Object Oriented Programming With C++


2) Improves the Understandability of the Application
3) Enhanced Security:
If an application needs to be extended or customized in later stages of development,
the task of adding new functions becomes easier without breaking existing code or
applications, thereby giving an additional security to existing application.
class a
{
int a,b;
public:
void setdata()
{
a=10;
b=55;
}
void getdata()
{
cout<<a<<b;
}
};
void main()
{
a obj;
obj.setdata();
obj.getdata();
}

Inheritance:

Inheritance is the process by which object of one class acquire the properties of
objects of another class.
In OOPs, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one.
The new class will have combined features of both the classes.

Features or Advantages of Inheritance:


1)

Reusability:
Inheritance helps the code to be reused in many situations.
The base class is defined and once it is compiled, it need not be reworked.
Using the concept of inheritance, the programmer can create as many derived
classes from the base class as needed while adding specific features to each
derived class as needed.
2) Saves Time and Effort:

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 5

Object Oriented Programming With C++

The above concept of reusability achieved by inheritance saves the programmer


time and effort.
Since the main code written can be reused in various situations as needed.

Example:
#include <iostream.h>
class Cpolygon
{
protected:
int width, height;
public:
void input_values (int one, int two)
{
width=one; height=two;
}
};

class Crectangle: public Cpolygon


{

public:
int area ()
{
return (width * height);
}

};

In the example above we have used the protected members of the class Cpolygon in the
class Crectangle and in the Ctriangle class. This is only possible through Inheritance.

Polymorphism:

Polymorphism is important oops concept. It means ability to take more than one
form.
In polymorphism an operations may shows different behavior in different instances.
The behavior depends upon the type of data used in the operation. For ExOperation of addition for two numbers, will generate a sum. If the operands are
strings, then the operation would produce a third string by concatenation.
The process of making an operator to show different behavior in different instance is
called as operator overloading. C++ support operator overloading.

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 6

Object Oriented Programming With C++

For Example:

Fig Polymorphism
The above figure shows concept of function overloading. Function overloading means
using a single function name to perform different types of tasks.

Dynamic Binding

Binding referes to the linking of a procedure call to the code to be executed in


response to the call.
Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time.

Message Passing

OOPs consist of a set of objects that communicate with each other.


Message passing involves following steps Creating classes that define objects and their behavior
Creating objects from class definitions and
Establishing communication among objects.
A message for an object is a request for execution of a procedure & therefore will
invoke a function in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the
function i.e. message and the information to be sent.
Example

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 7

Object Oriented Programming With C++

[4].Advantages/Benefits of Object Oriented Programming language


Simplicity:

1.

Software objects model real world objects, so the complexity is reduced and
the program structure is very clear.

Modularity:

2.

Each object forms a separate entity whose internal workings are decoupled
from other parts of the system.

Modifiability:

3.

It is easy to make minor changes in the data representation or the procedures


in an OO program. Changes inside a class do not affect any other part of a program,
since the only public interface that the external world has to a class is through the
use of methods.

Extensibility:

4.

adding new features or responding to changing operating environments can


be solved by introducing a few new objects and modifying some existing ones.

Maintainability:

5.

objects can be maintained separately, making locating and fixing problems


easier.

Re-usability:

6.

objects can be reused in different programs.

[5].Scope Resolution Operator::

In many situation, it happens that the name of global variable and the name of the
local variable are same .in this while accessing the variable, the priority is given to
the local variable by the compiler.
If we want to access or use the global variable, then the scope resolution
operator(::) is used.
The syntax for accessing a global variable using scope resolution operator is as
follows::
:: Global-variable-name;

Consider the following example

#include<iostream.h>
int c=8; //global variable
void main()
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 8

Object Oriented Programming With C++


{
int c=10; //local variable
cout<< c is<< c<< endl;
//it prints local variable
value 10
cout<< ::c is<< :: c<< endl;
//it prints global
variable value 8
}
Output:
C is 10
::C is 8

Scope resolution operator is also used when we want to use member function
(which declared in class) a outside of the class

The syntax for accessing a member function from outside class is as follows::
Function-return-type class-name :: function-name(arg1,arg2. argn)

Consider the following example

Class MyClass

class
demo
{
{
int n1, n2;
public:
int a,b;
void func1();
---------Function Declaration
public:
void setdata()
};
{
a::;
public cout<<enter
void MyClass::func1()
---Use of Scope Resolution Operator to write
function definition outside class definition
cin>>a;
{
cout<<enter b::
// Function Code
cin>>b;
}
}
void getdata();
};

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 9

Object Oriented Programming With C++

void demo :: getdata()


{
cout<<a is <<a<<endl;
cout<<b is<<b<<endl;
}
void main()
{
demo d;
d.setdata();
d.getdata();
}

[6].Friend Function::

A non member function cannot have an access to the private data of a class.
However there could be situation where we would like two classes to share a
particular function.

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 10

Object Oriented Programming With C++

In such situation, c++ allows the common function to be made friendly with both
the classes, thereby allowing 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.
The syntax for friend function is
class ABC
{
=======
public:
=======
friend void function1(void);
}
The function is declared with friend keyword. But while defining friend function. It
does not use either keyword friend or :: operator. A friend function, although not
a member function, has full access right to the private member of the class.

A friend, function has following characteristics.


It is not in the scope of the class to which it has been
declared as friend.
# include<iostream.h>
A friend
function cannot be called using the object of that
class sample
class. If can be invoked like a normal function without help of
any object.
{
It cannot access the member variables directly & has to use
int
b; name dot membership operator with member name.
an a,
object

public:
void setvalue()
It can be declared either in the public or the private part of a
{class without affecting its meaning.
Usually, it has the
object
a=
25; as arguments.
b = 40;
Consider }
the following example
friend float mean (sample s);
};
float mean(sample s)
{
return float(s.a + s.b)/ 2.0;
}
Void main ( )
{
sample x ;
x.setvalue();
cout << Mean Value = ;
mean(x);
}
output ::
Mean value = 32.5
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 11

Object Oriented Programming With C++

Member function of one class can be friend functions of another class. In


such cases they are defined using the scope resolution operator.

For Example::

class x
{ -----int fun(); // member function of x
};
class y
{
-----------------friend int x : : fun()
}; --------class abc ; //forward declaration
class xyz
{
int x;
public:
A friend function work as a bridge between the classes.
void setvalue(int i)
{
For Example:: x = i;
}
friend void max (xyz, abc);
};
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 12

Object Oriented Programming With C++

class abc
{
int a;
public :
void setvalue(int i)
{
a =i;}
friend void max(xyz, abc);
};
void max(xyz m, abc n) // definition of friend.
{
if(m. x > = n. a)
count << m .x;
else
cout << n.a;
}
main ( )
{
abc k;
k. setvalue (20);
xyz l;
l.setvalue (40);
max (l , k);
}
output is ::
40

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 13

Object Oriented Programming With C++

[7].Inline Function::

Every time a function is called, it takes a lot of extra time in executing a series of instructions
for tasks such as jumping to the function, saving registers, pushing arguments into the stack &
returning to the calling function. When a function is small, lot of execution time may be spent in
such overhead.

Solution to this problem is to use macro definition, but because macros are
not function, usual error checking does not occur during compilation.

To eliminate the cost of calls to small functions, c++ introduces inline


function. When inline function is called, the compiler replaces the function call with
corresponding function code.

Syntax of inline function is as follows:


inline function header
{
function body
}
inline int cube (int a)
{
return (a * a * a);
}
this function can be called as
c = cube(5);

All inline functions must be defined before they are called.

The speed benefits of inline functions decreases as function grows in size.


Therefore functions are made inline when they are small enough to be

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 14

Object Oriented Programming With C++


defined in one or two lines.

Following are situations where inline expansion may not works are:
[1]. For functions returning values, if a loop, a switch, or a goto exists.
[2]. For functions not returning values, if a return statement exists.
[3]. If function contains static variables.
[4]. If inline functions are recursive.

Example of inline function

# include <iostream.h>
inline int add (int x, int y)
{
return (x + y);
}
inline int subtract (int a, int b)
{
return (a b);
}
main ( )
{
int p = 15;
int q = 10;
cout <<add (p, q) << /n;
cout <<subtract (p, q) << /n;
}
output of program.
25
5

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 15

Object Oriented Programming With C++

class complex

[8].Function
Returning Object:
{
float x, y;
A function can not only receive objects as arguments but also can return them. Ex.
public:
void input (float real, float image)
{
x = real;
y = image;
}
friend complex sum (complex, complex);
void show(complex);
};
complex sum (complex c1, complex (C2)
{
complex c2;
c3. x = c1.x + c2.x;
c3.y = cl.y + c2.y;
return(c3);
}
void complex ::show(complex c)
{
cout << c.x << +j << c.y << \n;
}
void main ( )
{
complex A, B, C;
A.input (3.1, 5.65);
B.Input (2.75, 1.2);
C= cum (A, B);
cout << A; A.show(A);
cout << B; B.show(B);
cout << C"; C.show(C);
}
output of the program
A = 3.1 + j5 65
B = 2.75 + ji.2
C = 5.85 + j6. 85
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 16

Object Oriented Programming With C++

[9].Constructor:
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 construct the value data members of the class.
//class with a constructor
class Testconstructor
{
int m, n;
public:
Testconstructor(void); / constructor
declared
};
Testconstructor :: Testconstructor(void) //
constructor defined
{
m = 0; n = 0;
When a class contains a constructor like the one defined above, it is guaranteed that an
object created by the class will be initialized automatically. For example, the
declaration.
Testconstructor int1; // object int1 created
not only creates the object int1 of type Testconstructor but also initializes its data
members m and n to 0.There is no need to write any statement to invoke the constructor
function.
A constructor that accepts no parameters is called the default constructor.
The default constructor for class A is A::A(). If no such constructor is defined the
compiler suppliers default constructor. Therefore a statement such as
A a;
invokes the default constructor of the compiler to create the object a.
The constructor functions have some special characteristics.
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 17

Object Oriented Programming With C++

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 therefore, they
cannot return values.
They cannot be inherited, though a derived class can call the base
class constructor.
Like other C++ functions, they can have default arguments.
Constructors cannot be virtual.
We cannot refer to their addresses.
An object with a constructor (or destructor) cannot be used as a
member of a union.
They make implicit calls to the operations new and delete when
memory allocation is required. Remember, when a constructor is
declared for a class initialization of the class objects become
mandatory.

[10].Parameterized Constructors
The constructor Testconstructor(), defined above, initialized the data members of all
the objects to zero. However in practice it may be necessary to initialize the
various data elements of different objects with different values when they are
created. C++ permits us to achieve this objective by passing arguments to the
constructor function when the objects are created. The constructors that can take
arguments are called parameterized constructors.
The constructor testconstructor() may be modified to take arguments as shown below :

class testconstructor
{
int m, n;
public:
testconstructor (int x, int y);
//parameterized constructor
};
testconstructor : : testconstructor int x, int y)
{
m = x; n = y;
}
When a constructor has been parameterized, the object declaration statement such as
testconstructor int1;
may not work. We must pass the initial values as arguments to the constructor
function when an object is declared. This can be done in two ways;
By calling the constructor explicitly.
By calling the constructor implicitly.
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 18

Object Oriented Programming With C++


Testconstructor Int1 = Testconstructor (0, 100); //explicit call
This statement creates in testconstructor object int1 and passes the values 0 and 100 to
it.
The second is implemented as follows :
testconstructor int1 (0, 100); //implicit call.
This method sometimes called the shorthand method, is used very often as it is
shorter, looks better and is easy to implement.
Remember, when the constructor is parameterized, we must provide arguments for the
constructor. Program demonstrates the passing of arguments to the constructor
functions.
////////////////////////////// [CLASS WITH
CONSTRUCTORS] ///////////////////////////////
include <iostream.h>
class integer
{
int m, n;
public:
integer (int, int) ; // constructor declared
void display (void)
{
count << m = << m << \n;
count << n = << n << \n;
}
};
integer : : integer (int x, int y) // constructor defined
{
m = x; n = y ;
}
main()
{
integer int1 (0, 100) // IMPLICIT call
integer int2 = integer (25, 75); // EXPLICIT call
cout << \nOBJECT1 <<. \n;
int1.display();
cout << \nOBJECT2 << \n;
int2.display();
}
It display following output :
OBJECT1
m=0
n = 100
OBJECT2
m = 25
Prepared By: Mr. Vipul Tailor and Punam Aghera
n = 75

Page 19

Object Oriented Programming With C++

[11].Copy Constructor
A copy constructor is called whenever an object is copied. This happens in the following
cases:
When an object is create from another object during initialization (Class a = b)
When an object is created from another object as a parameter to a constructor
(Class a(b))
The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously. The copy constructor is used
to:

Initialize one object from another of the same type.

Copy an object to pass it as an argument to a function.

Copy an object to return it from a function.

If a copy constructor is not defined in a class, the compiler itself defines one.If the class
has
pointer
class
code variables and has some dynamic memory allocations, then it is a must to have
a{
copy constructor. The most common form of copy constructor is shown here:
int id;
public:
code ( )
{
} // constructor
code(int a )
{
id = a;
} // constructor again
code (code & x) // copy constructor
{
id = x.id; // copy in the value
}
void display (void)
{
cout << id;
}
};
void main ( )
{
code A =(100); // object A is created an initialized
code B (A); // copy constructor called
code C = A; // copy constructor called again
code By:
D; Mr.
// D
is created,
notPunam
initialized.
Prepared
Vipul
Tailor and
Aghera
D = A;
// copy constructor not called

Page 20

Object Oriented Programming With C++

cout
cout
cout
cout

<<
<<
<<
<<

\n
\n
\n
\n

id
id
id
id

of
of
of
of

A: ; A. display ( );
B: ; B. display ( );
C: ; C. display ( );
D: ; D. display ( );

}
Output:
id of A : 100
id of B : 100
id of C : 100
id of D : 100

Note that a reference variable has been used in the argument to the copy
constructor. We cannot pass the argument by value to a copy constructor.
When no copy constructor is defined the compiler supplies its own copy constructor.

[12].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 objects when the
objects are not of the same size, thus resulting in the saving of memory. Allocation of
memory to objects at the time of their construction is known as dynamic construction
of objects. The memory is allocated with the help of the new operator.
class myclass
{
int a,b;
public:
myclass()
{
a=0;
b=0;
}
myclass(int u,int v)
{
a=u;
b=v;
}
void getdata()
{
cout<<a<<endl<<b;
Prepared By: Mr. Vipul Tailor and Punam Aghera
}
};

Page 21

Object Oriented Programming With C++

void main()
{
myclass *s=new myclass[u];
for(int i=0;i<2;i++)
{
s[i]= new myclass(5,6);
s[i].getdata();
}
}

class string
{
char name;
int length;
public:
string() //constructor 1
{
length = 0;
name = new char[length + 1]; //one extrafor \0
}
string (char * s) //constructor 2
{
length = strlen (s);
name = new char[length + 1];//one extra for \0
strcpy (name , s);
}
void display (void)
{
cout << name << \n ;
}
void join (string & a, string & b);
};
void string : : join (string & a, string & b)
{
length = a. length + b. length;
delete name ;
name = new char [length + 1]; //dynamic allocation.
strcpy (name, a name);
strcpy (name, b. name);
};

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 22

Object Oriented Programming With C++

void main ( )
{
char * first = rani;
sring name1 (first), name2 (veer), name3 (raj), s2, s2;
s1. join (name 1, name 2);
s2. join (s1, name 3);
name1. display ( ) ;
name2. display ( );
name3. display ( );
s1. display ( );
s2 .display ( );
}
Output
Rani
Veer
raj
rani veer
rani veer raj

Program uses two constructors. The first is an empty constructor that allows us to declare
an array of string. The second constructor initialized the length of the string, allocates
necessary space for the string to be stored and creates the string itself. Note that
one additional character space is allocated to hold the end-of-string character.
The member function join () concatenates two strings. It estimates the combined length
of the strings to be joined, allocates memory for the combined string and then creates
the same using the string functions strcpy ( ) strcat ( ). Note that in the function join ( ),
length and name are members of the object that calls the function, while a. length and a.
name are members of the argument object a. The main ( ) function program
concatenates three strings into one string.

[13].Constructor overloadding
A constructor is said to be overloaded when the same constructor with different number of
argument and types of arguments initializes an object.
Constructors Overloading are used to increase the flexibility of a class by having more
number of constructor for a single class .By have more than one way of initializing objects
can be done using overloading constructors.

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 23

Object Oriented Programming With C++

class testconstructor
{
int m, n;
public:
testconstructor(); //default
testconstructor (int x, int y); //parameterized constructor
};
testconstructor : : testconstructor()
{
x=0;
y=0;
}
testconstructor : : testconstructor( int x, int y)
{
m = x; n = y;
}

So far we have used two kinds of constructors. They are;


testconstructor(); // No arguments
testconstructor(int, int); // Two arguments
In the first case, the constructor itself supplies the data values and no values are
passed by the calling program. In the second case, the function call passes the
appropriate values from main ( ). C++ permits us to use both these constructors in the
same class.
Now We can see another example of constructor overloading
class integer
{
int m, n;
public:
integer ( ) {m = 0; n = 0;) // constructor 1
integer (int a, int b)
{m = a; n = b;)

// constructor 2

integer (integer & i)


{m = i.m; n = i.n;)

// constructor 3

};

This declared three constructors for an integer object. The first constructor receives
no arguments, the second receives two integer arguments and the third receives one
integer object as an argument. For example , the declaration.
Integer I1;
Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 24

Object Oriented Programming With C++


would automatically invoke the first constructor and set both m and n of I1 to zero. The
statement
integer l2 (20, 40);
would call the second constructor which will initialize the data members m and n I2 to 20
and 40 respectively. Finally, the statement.
Integer I3(I2);
would invoke the third constructor which copies the values of I2 into I3. That is, it
sets the value of every data element of I2 to the value of the corresponding data
element of I3. As mentioned earlier, such a constructor is called the copy
constructor. The process of sharing the same name by two or more functions is
referred to as function overloading. Similarly, when more than one constructor is
overloaded, it is called constructor overloading shows the use of overloaded
constructors.

[14].Access specifiers:
Access specifiers defines the access rights for the statements or functions that follows it
until another access specifier or till the end of a class. The three types of access specifiers
are "private", "public", "protected".
Private:
The members declared as "private" can be accessed only within the same class and not
from outside the class.
Public:
The members declared as "public" are accessible within the class as well as from outside
the class.
Protected:
The members declared as "protected" cannot be accessed from outside the class, but can
be accessed from a derived class. This is used when inheritaance is applied to the
members of a class.

Prepared By: Mr. Vipul Tailor and Punam Aghera

Page 25

Vous aimerez peut-être aussi