0% found this document useful (0 votes)
22 views22 pages

Unit 2 Constructors(1).Ppt

Uploaded by

Inchara P
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)
22 views22 pages

Unit 2 Constructors(1).Ppt

Uploaded by

Inchara P
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/ 22

Constructors & Destructors

• The code relating to initialising data


members in the class be implemented in
the constructor.
• A destructor will perform destroy any
dynamic memory that was allocated in the
constructor or at some other point in the
object life, as well as releasing any system
resources that might similarly have been
assigned to the object during its life.
Constructors
• Same name as class
• No return type (not even void!)
• Can be overloaded
• Same name, differ by arguments they take
• One with no arguments is “default” constructor
• It is called constructor because it constructs
the values of data members of the class.
• A constructor allocates space for an object
and ensures that it is initialised correctly.
Example
int main()
{
ToD x, y;
return 0;
}

class ToD
{
private:
int h, m;
bool PM;
public:
ToD(){
cout << "ToD object created!" << endl;
}
};
What’s on the screen when the program runs?
• A constructor allocates space for an object
and ensures that it is initialised correctly.
• A constructor that accepts no parameters
is called the default constructor.
• They should be declared in the public
section.
• They can have default arguments.
• Cannot refer to their addresses
• They make implicit call to the operators
new.
Default Behaviour
• If no default constructor is defined then the
action on creation is to allocate store for
member objects;
• if default constructors are defined for these
member objects then these constructors
will in turn be called and the member
objects will be initialised.
• When constructors are declared in the
class,initialization of the class objects
becomes mandatory.
Parameterized constructors
• In practice it may be necessary to initialize
the various data elements of different
objects with different values when they are
created.This can be achieved by passing
arguments to the constructor function when
the objects are created.
• The constructor that can take arguments
are called parameterized constructor.
#include <iostream>
using namespace std;
class myclass { int a, b;
public:
myclass(int i, int j) {
a=i; b=j; }
void show() {
cout << a << " " << b;}};
int main(){
myclass ob(3, 5); or myclass ob=myclass(3,5);
ob.show();
return 0;}
Constructor
• Constructor functions can also be defined
as inline function.
• Parameters of a constructor can be of any
type except that of the class to which it
belongs.
class myclass { ...............
myclass(myclass) ;
}; // illegal
Constructor

•Constructors can accept a reference to its


own class as a parameter. In such case the
constructor is called a copy constructor.
class myclass { ...............
myclass(myclass&) ;
};
#include <iostream>
using namespace std;
class CRectangle { int width, height;
Public: CRectangle ();
CRectangle (int,int);
int area (void) {return (width*height);}};
CRectangle::CRectangle () {
Width = 5 ;height = 5; }
CRectangle::CRectangle (int a, int b) {
width = a; height = b; }
int main () {
CRectangle rect (3,4);
CRectangle rectb;
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
Constructors with default arguments
• Default arguments are formal parameters
that are given a value (the default value)
to use when the caller does not supply an
actual parameter value. Of course, actual
parameter values, when given, override
the default values.
class X
{ public: X(int arg1=7, int arg2=9);
....};
X::X(int arg1, int arg2)
{...
}
Constructors with default arguments

• The default argument constructor can be


called with either one argument or no
arguments.
• When called with no arguments,it
becomes a default constructor.
• When both these forms are used in a
class,it causes ambiguity for a statement
such as
• A a; //A::A() OR A::A( int x=0)
Dynamic Initialization of objects

Class xyz {
int x,y;
public : xyz( int a, int b) {x=a; y=b}
xyz( ){ } };
Int main()
{ xyz obj1,obj2;
cout <<“enter the value of x and y for object1”;
cin>>a>>b;
obj1= xyz(a,b);
Copy constructor
Class Point
{
public:
double x, y;
Point() { x = y = 100; }
Point(point &p)
{
x = p.x;
y = p.y;
}
};

Point a;
Point b(a); //call copy constructor
point c = a; // call copy constructor
Point d;
d = a; //copy constructor not called
Dynamic constructor
# include <iostream>
# include <cstring>
class str
{ char *name; int len;
Public: str() {
len=0;
name=new char[len+1];}
Dynamic constructor
• str(char *s) {
• len=strlen(s);
• name=newchar[len+1];
• strcpy(name,s); }
• void show() {
• cout<<"NAME
IS:->"<<name<<endl; }
• void join(str &a,str &b);
• };
Dynamic constructor
void str::join(str &a,str &b)
{ len=a.len+b.len;
delete name;
name=newchar[len+1];
strcpy(name,a.name);
strcat(name,b.name); }
main()
{ clrscr();
char *first="HARISH";
str n1(first),n2(“ANAND"),n3("PRATIK"),n4,n5;
Dynamic constructor
n4.join(n1,n2);
n5.join(n4,n3);
n1.show();
n2.show();
n3.show();
n4.show();
n5.show();
}
What is a destructor?
• It is a member function which deletes an object.
• A destructor function is called automatically
when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing temporary variables ends
(4) a delete operator is called
• A destructor has:
(i) the same name as the class but is preceded by a
tilde (~)
(ii) no arguments and return no values
destructor
class string { private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor };
string::string(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}
string::~string()
{ delete []s; }
destructor
• If destructor is not defined, the compiler
generates a default destructor .
• When a class contains a pointer to
memory you allocate, it is your
responsibility to release the memory
before the class instance is destroyed.
Implementation of Destructors
#include <iostream>
Using namespace std;
Intint main() {
Int count =0; cout<< “ enter main block”;
Class alpha alpha A1,A2,A3,A4;
{
{ public: alpha()
cout<<“\n\n enter block 1\n”;
{ count++; alpha A5;}
cout<<no. of obj created”<<count; { cout<<“enter block2\n”;
alpha A6;
} }
~alpha() cout<<“ re enter main”;
{ cout<< no. of obj destroyed”<<count; return 0;
}
count--; } };

You might also like