0OPS Introduction: Compilers
0OPS Introduction: Compilers
UNIT1
0OPS Introduction
1.1 Introduction to Object Oriented Programming
Function 1 Function 2
Function 3
Function 4 Function 5
The main features of Procedure Oriented Programming are as
follows:
Visit us at http://www.dotcombooks4u.com
2/OOPS Introduction
Yisit us at htt
Object Oriented Concepts and Programming/3
Objectl Object 2
Data Data
Functionss Functions
Object 3
Data
Functions
.
1. In object oriented programming, the application programs are
organized, designed and written around the data making the
object oriented programming data centric.
iii) Encapsulation
It is a mechanism by which data and functions are
packed together into a single unit called class.
Encapsulation provides data security, i.e., the data inha
particular class is not accessible to the outside world. The
functions that are packed in same class can have direct
access to the data of particular class.
iv)Abstraction
It is an idea of representing necessary details without
including background details which are needed for
presentation. This helps in reducing the complexities im
understanding the unnecessary details, that are really not
so important or needed. Class use the concept of example
of Abstraction.
C C++
is aprocedure orientedC++ is object oriented
C more
programming language where programming where
on data rather
more emphasis is laid on emphasis is laid or
on procedures
procedures or algorithms rather than
|
algorithmns.
than data.
Visit us at http:/lwww.dotcombooks4u.com
6/OOPS Introduction
Visit us at http://www.dotcombooks4u.com
Object Oriented Concepts and Programming/7
Example:
cout'x="<<x<<endl;
The above statement tries to write the value of x on the screen or
monitor.
Example:
cin>>"x;
The above statement waits for the user to enter a value through the
keyboard.
Visit us at http://www.dotcombooks4u.com
8/0OPS Introduction
,
1.1.6 Comments in C++
In C language, multiline comments are used. In C, the comments
are enclosed between_* and */. In C++, we have single line
comments starting with symbol two forward slashes i.c., //. Any
comment should be preceded by //. C++ supports both types of
comment styles. The lines that are commented will never be a part
of compliation code.
Programn
C+ program.with commenis /+This is comment line of C
Supported in C++ also
I/Sample C++ program -This s comment line in C++
#inciudeciostream
:
s Using namespace
int main)
std;
(l endl =n
//Comments helps in documentablity
coute"this is a c++ program"<<endi
return 0;
Program 1.2
#includeciostream.h>
using namespace std;
int main()
int i;
10;
i = "<<i <<endl; Cout ce" i ';
cout<<"i
int j:
j=10;
cout<<"i = "<<j <<endl;
refurn 0:
Program :
#includeciostream.h>
USing namespace std;
int main()
Visit us at http:
// www.dotcombooks4u.com
Objoct Orienied Concepts and Programming/11
intp 10;
int &r = p:
cOufke"p= "<<p <<'r = <<r < endl;
"
return 0;
d. Like int, float and double, the reference variable can also be
made to reference pointer.
:
A reference to an array is allowed in C++.
Program 1.4
y
#include<iostream.h>
U USing namespace std;t .
t 10 int main\|
bool a 25;
Visit us at http://www.dotcombooksdu.com
12/OOPs Introduction
int b = true;
int c false
cout<<"a = "<<a <<end;
cout<<"b = "<<b <<endl;
cout<<"c = "<<c <<endl;
return 0;
3 Program g
#includeciostream.h>
USing namespace std;
float add (fint, float): // function prototype
int main()
intx =2;
float y = 3.6, z;
z add(x.y);
Cout<<"x= "<<x << "y = "<<y <<"="<<z <<endl;
return 0:
Programn .
#includeciostream>
USing namespace std;
int addchar); /function profotype
int add(nt, int); //function prototype
float add(int, float): //function prototype
int main()
char c = 'S';
intx1 = 2, x2= 3;
float fl = 2.2;
int d.e:
d add(c);
e add(x1,x2):
float f3 = add(x2,f1);
cout <<"c = "<<C<<d<<endl;
cOut <XI= "<<Xl<<"x2 = "<<x2<<"e = "<<e<<endi;
cout <<"x2 = "<<x2<<"fl = "<<fl<<"3 = "<<{3<<endl;
return 0;
return(c1+1);
returnil+i2):
returni+H;
Program
#includeciostream>
Using namespace std;
int i2, int i3 =6); I/i3 is assigned a default value of 6
int addint il,
Visit us at http:// www.dotcombooks4u.com
16/OOPS Introduction
int main(0
int result.a.b;
a = add(10,20);
b=add(10,20,30); i3 = "<<i3<<" a =
"<<a<<end:
i2 = "<<i2<<"
cout <<"il = "<<il<<" = "<<i2<<" 13 "<<i3<<" b="<<b<<end:
cout <<"il = "<<il1<<" i2
retum 0: }
int addint x, int y, int z}
{
returnx +y+7); }
function-body
Example
inline double cube(double a)
return (a'a"a);
int x = 10;
intx= 1;
***
memory locations
Two declarations of x refer to two different
containing different values.
= 10; Block 1
intx
Program
#include <iostream>
int n = 12: // A global variablet
int main
1.2.1 Structures in C
Structures in C language provides a method for packing together
data of different types. It is convenient. for handling a group of
logically related data items. The User-defined daa type is used
with a template to define its data properties. Once the structure
type has been defined, it is necessary to create variables of that type
using declarations that are similar to the buit-in type declarations.
Structure can have arrays, pointers or structures as members.
Example:
struct student|
char name|20];
Example:
struct student A; //C declaration
In the above statement, A is a variable of type student and has
thre
member variables as defined by the template. Member variables
can be accessed using the dot or period operator as:
strcpy(A.name,"ABC");
A.roll_number=1;
A.total_marks=595.5;
Limitations of C Structures
A
a Cdoes not allow the struct data type to be treated
like built-in
types.
Example:
struct complex{
float x
C float y
Struct complex cl, c2, c3;
Visit us at
http: // www.dotcombooks4u.com
Object Oriented Concepts and Programming/21
Example
Declaration student A is valid in C++ but it is not in C language.
Public Area
Entry allowed
Data
to publie area.
Functions
Visit us at http:/www.dotcombooks4u.com
24/0OPs Introduction
ITEM
Class: 1TEM
getdata()
DATA
number T
cost putdata()
FUNCTIONS
getdata( )
putdata()
Example
x
item x;// memory for is created.
the-
statement creates a variable x of type item. In C++,
The above
are known as objects. So x is called an object of typc
class variables
allows to declare more than one object in one
item. It also
statement.
Example
item x, y, Z;
x, y, Zj
The above code would create the objects x, y and z of type item. It
is prefer to declare the objects close to the place where they are
used and not at the time of class definition.
The members of classes declared with the keyword class are private
keyword
br default and members of, classes declared with the
struct or union are public by default.
use one of the access
To control the access of a class member, you
class membcr
specifiers public, private, or protected as a label in a
list.
Program
struct A {
friend class C;
private:
int a;
public:
ini b;
protected:
int c:
siruct BA
void f() {
b=2
C 3;
struct C
void f{A x{
X.a = 4
x.b = 5;
x.C = 6:
:
int main(0 {
A y:
Y.b 8;
BZ,
= 11;
z.b
The access of data members A:a A:b, and A:c in various scopes of
the above examplecan berepresented in the table as follows:
Scope A::a A::b A::c
function No accesSs. Access. Member Access. Class B
.B:f0 Member A::a A::b is public. inheritsfrom A.
15 is private.
function Access. Access. Member Access. Class Cis a
C::0 Class C is a A::b is public. friend of A.
friendof A.
object y No access. Access. Member No access. Member
in Member y.a y.a is public. y.cis protected.
main() is private:
object z No acccss. Access. Member No access. Member
in Member z.a z.a is public. Z.c is protected.
main)L is private.
Visit us at http: // www.dotcombooks4u.com
Object Oriented Concepts and Programming/27
function body
http://www.dotcombooks4u.com
Visit us at
28/OOPS Introduction
Several different classes can use the same function name. The
membership label will resolve their scope. Member functions can
access the private data of the class. A non-member function cannot
do so. A member function can call another member function
directly, without using the dot operator.
Example:
void item:: getdata(int a, float b)o N
number=a;
cost= b;
initialized:
int a = 0;
int a (0);
Programn
I/ initialization of variables
#include ciostream> .
Example
struct point
int x;
int y;
point "p
p new point;
p->x 12;
p->y = 34;
For an object say, class demo, type of this will be demo* const this.
For a n object of say class temp, type of this will be temp*const this.
Program
#include <iostream>
Using namespace std;
class MyClass
int data
public:
MyClass() {daia=100:); rdija thga
void Printi ();
void Print2():
MyClass a;
a.Printl():
a.Print2():
100
4
1.3 Exercise
A. Long Answer Questions
1. Explain about Procedure Oriented Programming.
2 Explain about Object Oriented Programming8
3. Differentiate between Procedure Oriented Programming and
Object Oriented Programming.
4. Explain about Reference Variables with an example.
5. Explain about bool data type with an example.
6. Explain about Function Overloading with an example.
7. Explain about Function Overloading with default parameters
with an example.
8. Explain about Inline Function with an example.
9. Explain about Scope Resolution Operator with an example.
10. Explain about access specifiers and their characteristics.
11. Explain about Classes in C++.
12. Explain about Objects in C++.
13. How functions can be defined and accessed outside a class?
14. Explain about Arrow Operator with an example.
15. Explain about 'this' pointer with an example.
16. Write a C++ program to implement
the usage of reference
variables.
17. Write a C++ program to calculate area of rectangle, triangle
circle using Function Overloading.
18. Write a C++ program using Function Overloading with
default parameters.
19. Write a C++ program to implement the usage of Scop
resolution operator.
20. Write a C++ program to implement the usage of
this pointe
Visit us at http://www.dotcombooks4u.comm
34/0or Introduction
inheritance.
4. We can create one or more objects of same class type.
5. By default, members of structure are public and that of class
are privatc.
6. A variable can be tied with several references.
H39AH2 ibn
://www.dotcombooks4u.com
Visit us at http
Management, Co1struco
36/Morc on ++ Classes and Object, Dynamic Memory
Menory
Memory
UNIT 2
Object,
ynamic
Dynan
More on ++Classes and
Management, Constructor & Destructor
class.
another
2.1 More on Classes and Objects menmber variablee of
or a
to have a Class as a
lt is possible
Program
Header File: shape.h
#ifndef_SHAPE_H
#define SHAPE_H
class FRectangle
Length(l), Width(w)
public double w= 0]:
Kectanglefdoublel 0,
lgt)
void setlength(doublewdt):
void setWidth double
const:
double getLengthf)const
double getWidth() const:
double Perimeter()
double Areal| const
void Properties()
private:
double Length;
double Width:
#endif //_SHAPE_H
#include <iostream.h>
#include "shape.h"
Visit us at http:// www.dotcombooks4u.com
eObject Oricnted Concepts and Programming/37
void FRectanglesetLength|double
Igt
Length= lgt:
void FRectangle::setWidth(double
wdt)
Width = wdt;
return Width;
void FRectangle:Properlies()
#ifndef BRICK H
#define BRICK_H_
#include "shape.h"
class Brick
public:
Brick()
void setThickness(double Tck);
VoId setDimensions(double l, double w, double i
void setColor(char clr);
void settexture(char ixr);
char getColor() const,
char getTexture() const;
double olumel) const;
void Display():
private:
FReciangle shape
char Color:
char Texture;
double Thickness; one} muts
BRICK_HL
tendif //
Source File: brick.cpPP
#include ciostream.h>
i#include "brick.h"
Thickness = Tck;
Color clr;
Visit us at http:// www.dotcombooks4u.com
Object Orienled Conccpts and Programming/39
Toxlure= txr;
shape.setLengih ();
shape.setWidth(w);
sellhickness(1:
void Brick::Display()
#include"shape.h"
#include "brick.h"
brick.Displayl:
class Shape{
double width;
double heighi;
public:
void display() {
COut"Width and height are "<<width <<" and "<< height <
"\n;
/ accessor functions
double getWidth(){return width; }
double gatHeight{} {return height;}
void setWidth{double w) { width = w; }h erii phia
void setHeight[double h} { height = h:}
double area() {
returngeiWidth()"getHeight()/2det sr
void st.owStyle{) {
Out << "Triangle is"<< style <<"\n";
Triangle
fl
Triangle 12:
t1.setWidth(4.0):
t1.setHeight(4.0):
strcpy(t1.style, "isosceles); vets, ris
t2.setWidth(8.0);
12.selHeight(12.0);
Visit us at http://www.dotcombooks4u.com
CousiruclU.
1nnageunent,
++ Classes and Object, Dynamic Memory Manns
42/Mor on
strcpy(12.stylo, "right"):
11.showStyle();
11.display():
cout << "Arca is "<< 11.areal) << "\n:
12.showStyle();
12.display):
coul << "Area is << 12.area() <<"\n;
"
return 0:
Member Functions
in two placcs, they are
defined
Mcmber functions can be
a) Outside the class definition
b) Inside the class definition
inside a class have to be detincd
Mcmber functions declarcd Their dcfinitions are like normal
SCparately outside the class. have the function hcader
should
functions. The member functions support the old version of
C++ does not
and function body. Since for
definition, the ANSI prototype form must be used
function
defining the function header.
function body 1
92.
In the above syntax, the membership label class-name tells the
compiler that the function function-name belongs to the classnamc.
a. Several different classes can use the same function name. Ihe
'membership label' will resolvc their scope
A
b. Member functions can access the private data of the class.
non-member function cannot do so.
Programn -*
#include<iostream>
Using namespace std;
class item
ptrijiobieg:1e
r
void getdatafint a, float b): 2
void putdata(void); }:
b}
void item : getdatafini a, float
number=a;
cost = b; T
void item:: putdata(void)
<<
<< number "\n
" fU,
cOut << "Number=
= << cost << "\n":
" }
cout <"Cost
int main(
i.temilil.getdata|5,12.5);
1.putdatal); els nos a
www.dotcombooks4u.com
Visit us at http://
Destructor
Constuctor &
44/ Morr on t+ gement, Co"
Classrs and Object, Dynamic Memory Mamgement,
replace the
Defining Member functions clas to
Inside the function is inside the
One more method of defining a member definition
definitionted as an
an
function trcated
cd
function declaration by the actual class, it is apply to an
class. When a function is defined inside a aPPy
limitations thatfunctions are
inline function. The restrictions and small funce
inline functions are also applicable here.
defined inside the class definition.
Program
class item
int number;
fioat cost:
public:
void getdata(int a, float bl: //declaration
// inline function the ciass
void putdata/void) { // definition inside
Cout << "Number = "<< numbeer
cout << "Cost = "<<cost;
int main
item il
il.getdata(5,12.5]
il.putdatal}:
Example
class sample{
int m;
void read(void);
public:
// privale member function
void update (void);
Data Members
Data members include members that are declared
with any of the
fundamental types, as well as other types, including
pointer,
reference, array types, bit fields, and user-defined types. You
can
declare a data member the same way as a variable, except
that
explicit initializers are not allowed inside the class definition.
However, a const static data member of integral or enumeration
type may have an explicit initializer.
A class can have members that are of a class type or are pointers or
references to a class type. Members that are of a class type must be
of a class type that has been previously declared. An incomplete
class type can be used in a member declaration as long as the size
of the class is not needed. For example, a member can be declared
that is a pointer to an incomplete class type.
Management,Rcment,
46/Morr on ++ Clnsses and Olject, Dynamic Memory contain
it canMember
type X, but X.
is of cls of return type
of ty
A class X cannot have a member that is
ereces to hat
static
pointers to X, references to X, and type *
a
functions of X can take arguments of
of X.
Example
class X
X *xptr;
X &xref;
static X xcount;
X xfunc(X;
the clasSs.
2.1.2 Friend Functions accessed from outside
members cannot be the private data of
ne private
Non-member function cannot have an access
requires
to
to share a particular
two classes
a class. In some situation,
function.
classes manger and scientist
are two
Example : Suppose if therefunction income tax(0 to.operate on
the
which would like to use
a
handles this case by allowing the
classes. C++ classes, allowing
objects of both these friendly with both
common function to be made private data of these classes. Such a
access to
the function to have of any of these classes.
be a member
function need not
function "friendly" to a class, simply declare
To make an outside
this function as a friend of
the class as follows: il "
class ABC{
public:
friend void xyz(void) // declaration b st
Example:
class x {
class y{
friend intx:: fun1(); // fun1 of x is friend of y.
class z of
friend class x; // all member functions
7/ x are friends of z es of
copies
local
crence. Here address of the
A friend function can
be called by to the on the actual
Instead, pointer rks
works
the objects are not made.
called function directly
the values of the
object is passed and the used to alter private
vate members
call. Method can values of
object used in the th
Altering
private members of a class.
principles of data hiding
is against the basic
Programn
#include <iostream.h>
Using namespace std;
class myclass
int a, b;
public: x):
friend int sum(myclass
j):
void set abfnt int
i,
i, int j)
void myclass:set abfint
a =i:b=
int sum(myclass x)
{
return x.a t x.b;
int main|
myclass n;
n.set ab(3, 4);
Visit us at http:// www.dotcombooks4u.com
49
h39,at 4aiObject Oriented Concepts and Programming/
Program
#include<iostream>
Using namespace std;
class Storage
private:
int m_nvalue;
double m_dValue:
public:
Storageint nValue, double dValue)
m_nValue = nValue;
m_dValue = dValue;
private:
bool m_bDisplaylntFirst;
public: m_bDisplaylntFirst=
Display(bool bDisplayintFirst) {
bDispiaylntFirst:}
if (m_bDisplaylntFirst)
cOut << CStorage.m_nValue <<""<
CStorage.m_dValue << end
Visit us at http: www.dotcombooks4u.com
/
50/More on ++ Classes and Object, Dynamic Memory Management, Constrier
int main()
Storage cStorage(5,6.7);
Display cDisplay(false);
cDisplay.Displayltem(cStorage};
return 0:
Display's
ny of
any
Because the Display class is a friend of can access the pfriend
Storage, private
members that use a Storage class bject though Display is a
even of
members of Storage directily. First, access to the *this pointer
Display has no direct friend of Storage, that
Oge objects. Second, because Displav is a
you want two
torage If
aoes not mean Storage is also
Classes to be friends of each
a friend of
other.
Display.
both must
friend of B, and
B
declare
is a
the
friend of ,
other as a
that
friend. Finally, if class A is a C. When using friend functions-and
does not mean A is a friend of friend function or class to
VIolate
classes, because it allows the class change, the details of the
encapsulation. If the details of the Consequently, limit your use of
friend will also be forced to change.
minimum.
friend functions and classes to a
Example
class employeef
char name[30];
float age
public:
void getdata(void);
void putdata(void);
Example
manageri-getdata(0
memory the same way as a
An array object is stored in. the
of object is
multidinmensional array. Only the space for data items by all the
spearately and used
created. Member functions are stored
objects.
class object will be as follows:
Inside the memory, the array of
s
name manager[
age
name managerl]
rage
manager 2
name
age
Programn
A
#include <iostream.n> h; rI
class cl{
int i;
public:
http://www.dotcombooks4u.com
Visit us at
ctor
& Dest
52/More on ++ Classes and Object, Dynamic Memory Managcmcnt, Constructor
int main(
clrscr()
cl ob[3] = {1, 2, 3): // initializers
int i
for(i=0: i<3; i++)
cout ob[ü.get i) <<"\n":
return 0;
Program
closs refurnObjecl{
int p;
public:
returnObject manipulate|returnObject ro)
ro.p100:
void display () {
cout «< p:}}
int main()
2.1.8 Namespaces
Namespaces allow to group entities like classes, objects and
functions under a name. This way the global scope can be divided
in "sub-scopes", each one with its own name.
The format of namespaces is as follows: om,lni
Namespace identifier
Entities
Visit us at http:/www.dotcombooksdu.com
&Destrucro
Management, Constructor
54/More on ++ Classes and Object, Dynamic Memory of
the sctthe
and entities
Where identifier is any valid identifierare
is in
within
included
classes, objects and functions that
namespace.
Examplee
namespace myNamespace
int a, b;
variables declarcd
case, the variables a and b are normal access these
th
In this In order to have to
within a namespace called myNamesp
myNamespace
namespa previous
variables from outside the access the
mple, to
use the scope operator :. For we can write:
variables from outside myNamespace
name from a namespacc
keyword using is used to introduce a
Ihe
into the current declarative region
1Program
LAA// namespace exampie
Using .
finclude <iostream>
Using namespace std;
námespace first
intx= 5;
namespace second
0
a93IU
S
AE
*Idouble x = 3.1416;
1512001 E 3rz2i9 i 52
int main ()
Using namespace first;
cOut <<x << endl;
return 0;
Visit.us.at http://www.dotcombooks4u.com
estruclor
S6/ More on ++ Classes and Olject, Dynamic Memory Management, Coustructor & Dest
elementsS
In this case, the system dynamically assigns space tor five e
for five he
of type int and rcturns a pointer to the first element
o
points
sequence,which is assigncd to hobby. Therefore, now, hobp int.
to a valid block of memory with space for five clements or
assigning
The difference between declaring a normal array anas
y and to
array
to be a
dynamic memory to a pointer is that the size of an at the
constant value, which limits its size to what we dec hercas whercas
moment of designing the program, before its exccution memory during
during
the dynamic memory allocation allows us to assign var. or
any by our
the exccution of the program (runtime) using requested by
constant value as its size. The dynamic memory nory rcque
memory heap.
program is allocated by the system from the
Program
#include <iostream.h>
USing namespace std;
int main)
int "p;
P new int: // allocate space for an int
p 100;
cout << "At" << p <<"";
cOut << "is the value"<< "p<< "\n"
delete p:
return 0
2.2.3 o
Dynamic Memory Deallocation memory is usually limited to
Since the necessity of dynamic
moments within a program, once it is no longer necded it
specific
freed so that the memory becomes available again for
should be
requests of dynamic memory, and it can be done with the
other
help of delete operator.
Program
#include siostream.h>
Jsing namespace std;
ind main(
clrscr()
int "p;
p new int (87): // initialize to 87
cOut <<"At" << p <<"";
cout <<"is the value "<<*p <<"\n";riWai1
delete p
return 0;
b
2.2.4 "Set_New_Handler" Function
The format of function is as follows:
ncw_handler set_new_handler (new_handler new p) throw()0
Program
#include <iostream>
#include <cstdlib>
#include <newV> std;
Using namespace
void no_memory1to(){allocate memory!\n;
COut << "Failed
exit (1);
() {
int main
new_handler(no_memory); GiB..."
set to allocate
"Atfempting[10241024*1024]:
1
cOut <
char p= new char
cout << "Ok\n":
deletellp:
retun 0:}
int m, n;
public:
integer(void);// constructor is calledisits ssrale
Visit us at http://www.dotcombooks4u.com
Object Oricnted Conccpts and Programming/ 59
Example
Suppose if the declaration is integer intl;
Tt not only creates the object
intl of type integer but also initializes
its aata members m and n to zero. There is no need to write any
staterient to invoke the constructor function (as with normal
function). If a 'normal' member function is defined for zeroo
initialization, it is necessary to invoke this function for each of the
objecis separately. It would be inconvenient if there are a large
number of objects.
Program
#include <iostream.h>
#define SIZE 100
// This creates the class stack.
class stack {
int stck[SIZE];
int tos:
public:
stack(); // constrUctor 3iU .o
stack();// destructor
void push(int i):
intpopl)
/stack's constructor functic a
siack:stack{)
tos = 0:
cout << "Stack Initialized\n":
}
cout"Stack Destroyed\n":
i)
void stack::push(int
if(tos==SIZE) {
stcktos]=i;
tos+4
int stack::pop(
if(tos==0)
cout <<"Stack underflow.\n":
return 0:
fos
return stck[tos];
int main(0
2.3.2 Characteristics
of Constructor
a. It should be declared in
the public section.
b. It is invoked automatically
when the objects are created
C. t do not have return types, not even void and therefore, they
cannot return values.
Default Constructor
A constructor accepting no parameters is called the default
constructor.
can be as follows:
The explicit declaration
integer intl = integer (0, 100);
It is also possible
to define constructor functions as inline
functions.
Example
class integer{rat
int m,n;
u
public:
integer(int x, int y)//inline constructor
m=x; ny
Example:
class A {
's
i public:
A(A); ; 3
Programn
#include ciostream.h>
class X{
int a;
public:
X{(int j) {a
=i}
intgeta) {return a:} ard
intmain():
{
C. Copy Constructor s as a
copy
Constructor can accept a rcfercnce to ilsthrough a copy
parameter. The process of initializing A COPy
initialization. as itself
constructor is known as copy
the
as
samecompiler
constructor takes a reference to an object of
as an argument. When no constructor is de
supplies its own.
follows;
callcd is as same
The situations where copy constructor is object of the
() When a new objcct is initialized to
an
class.
function by valuc
(i) When an object is passed to a
from a function by vauc.
(11) When an objcct is returned
temporary ODjec
(iv) When the compiler generates a
constructor. If i1.
copy
The statement i2=i1 will not invoke the
simply asigns the
statement is legal and
and i2 are objects,
values of il to i2, member-by-member.
public:
A(A &);
is valid.
In such cases constructor is called the copy
constructor.
Example
class integer |
int m, n;
public:
integer() m=0; n=0;}
integer(inta, int b) {m=a; n=b;}
integer(integer & i)
m=i.m;n=i.n;}
Program
tinclude <iostream.h>
class pwr {
double b:
int e:
double val;
public:
pwr(double base, int exp);
double getpwr() { return val:}
pwr:pwr[double base, int exp)
b base;
e = exp:
val= 1
if(exp==0) return;
*
b;
for: exp>0; exp--) val= val
int main()
return 0
Program
#include <iostream.h>
class cube{
int x, y, z;
r public:
cubeint i=0, int j=0, int k=0) {
x=i;
z=k;
int volumel) {
return x'yz
int main()
clrscr():
cube a(2,3,4), b;
cOut < a.volumel) << endl
<< b.volume();
COut
return 0
f. Dynamic Constructors
t e The constructors can also be used to allocate memory while
creating objects.It enable the system to allocate the right
amount of memory for each object when the objects are not of
the same size, resulting in the saving of memory. The
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.
Visit us at http:://.www.dotcombooks4u.com
Destruc
"clor &
Managcmcnt, Constructor
68/Mor on ++ Classes and Object, DynamicMcmory
objccts
thaj
2.3.4 Destructor the cto the
A destructor as name implies, is uscd to destroy th
construd as th
constructor. Like a ne
have been created by a name is tne
destructor is a member function whosc
i.e., ""
class name but is preceded by tilde as:~integcr) (}
program
can be defined om.practico
the
The destructor for the class integer upon exit is to
It is invoked implicitly by thc compiler space fo
spa
accessibie:emory nory
to clean up storage that is no
program
longer
since it n
relcases memory the
cmory in the
declare destructors in a uscd to allocate
future use. Whenever new is free that memory
constructors, should use delete to ws:
as tO
matrix class can be defined
The destructor for the
matrix:: ~matrix()
for(I-0;I<d1;l++)
delete pl;
delete pl
any
Characteristics of Destructor argunment nor does it return
2.3.5 takes any
a. A destructor never
a class.
value.
destructor can be defined for
Only one
b.
Destructor cannot be overloaded. objects go out of scope, a
C.
required since the pointers to
d. It is implicitly.
destructor is not called
EXERCISE
2.4
LONG ANSWER QUESTIONS accessing Member Functions
A ways of
1. Explain about different
in a class.
Friend Functions with an example.
2 Explain about
Explain about Friend Class with an example.
3.
how to access array of Class Object.
AExplain about
Visit us at
http://www.dotcombooks4u.comn
Object Oriented Concepts Programming/0
and
Cinline
d) virtual
. c)
The
destroy
operator is uscd to create a heap memory space
for an object of a class.
a) new
b) delete
c) arrow
destroyed.
***