Presentation is loading. Please wait.

Presentation is loading. Please wait.

CONSTRUCTORS AND DESRUCTORS

Similar presentations


Presentation on theme: "CONSTRUCTORS AND DESRUCTORS"— Presentation transcript:

1 CONSTRUCTORS AND DESRUCTORS
Pradeep Swami KV Jhunjhunu

2 INTRODUCTION The most important OOP features are not only implemented but also tied together by the single most important C++ enhancement, a CLASS. But definition of class only creates a data type. The objects of a class type have to be created and initialized separately as an object. An object, in effect, is a region of memory storage, created at run time. C++ provides a mechanism for initializing an object when it is created (Constructors) and when the same is not needed, C++ defines a way to scrap it off, by means of a destructors.

3 CONSTRUCTORS A member function with the same name as its class is called Constructor. Constructors are called automatically when an object is created of that class. Constructors are used to initialize the object to a legal initial value for the class. The have no return type, not even void.

4 EXAMPLE class student { private: int rollno; float marks; public:
. student( ) // constructor rollno= 0; marks= 0.0; } }; // Now forth, whenever an object of the student type will be created , the compiler will automatically call the constructor student :: student( ) for the newly constructed object.

5 NEED FOR CONSTRUCTORS { int rollno; float marks; }; int main( ) {
A structure or an array in C++ can be initialized at the time of their declaration. e.g. struct student { int rollno; float marks; }; int main( ) { student s1=(0,0.0); int a[5] = {1,2,3,4,5}; }

6 But such initialization does not work for a class because
the class members have their associated access specifiers. They might not be available to the outside world. e.g. class student { private: int rollno; float marks; public: ___________ // public members ___________ }; int main( ) { student s1=(0,0.0); // illegal ! }

7 student s1; // create an object s1.init( ); // initialize it
There is an alternative solution to it. If we define a member function (say init() ) inside the class to provide the initial values, as shown below: class student { private: int rollno; float marks; public: void init( ) { rollno=0; marks=0.0; } }; int main( ) student s1; // create an object s1.init( ); // initialize it

8 See now the function init( ) can provide initial values, but still the programmer has to explicitly invoke it. What if, the programmer fails to invoke init( ) ? The object in this case, is full of garbage and might cause havoc in your program. Then what is the way out? Simple, take the responsibility of initialization away from the programmer and give it to the compiler. Every time the object is created, the compiler will automatically initialize it by invoking the initialization function. And that is, you know it ,a Constructor!

9 DEFAULT CONSTRUCTOR A constructor that accepts no parameter is called the default constructor. With a default constructor ,objects are created just the same way as variables of other data types are created. e.g. X obj1; will create the object obj1 of type X by invoking the default constructor. If a class has no explicit constructor defined, the compiler will supply a default constructor. The default constructor provided by the compiler does not do anything specific. It simply allocates memory to data members of object.

10 PARAMETERIZED CONSTRUCTORS
Like other functions you can also write constructors that can accept parameters. Such constructors are called parameterized constructed (or regular constructors). Once you declare a constructor with arguments, the default constructor becomes hidden. You cannot invoke it. A constructor with default arguments is equivalent to a default constructor.

11 class A { int i; float j; public: A (int a=0, float b=100.0); // prototype declaration with }; default arguments A::A (int a, float b) // constructor definition { i=a; j=b; } int main( ) { A obj1 (23, ); // values passed for obj1 A obj2;

12 SIGNIFICANCE OF DEFAULT CONSTRUCTORS
The default constructors are very useful when you want to create objects without having to type the initial values or want to initialize objects every time with pre specified initial values or if you want to create an array of objects. You cannot create array of objects unless your class has a default constructors.

13 // code snippet 1: Default constructor not available
class test { int a; char b; public: test ( int i , char j) //This is not default constructor { a=i ; b=j ; } }; int main( ) { test tarray [5]; //Error! (as array can’t be created because default constructor is not available) test newobj ( 31,‘z’); //Valid as corresponding constructor // accepting the arguments is available.

14 // code snippet 2: Default constructor is available
class test { int a; char b; public: test ( ) //THIS IS DEFAULT CONSTRUCTOR { cout<< “Default constructor being called”; } test ( int i , char j) //Constructor with arguments { a=i ; b=j ; cout<< “Constructor with arguments called”; }; int main( ) { test tarray [5]; //Valid! (as array can be created because default constructor is available) test newobj ( 31,‘z’); // constructor with arguments will be called

15 INVOCATION OF CONSTRUCTORS
With a parameterized constructors for a class, one must provide initial values as arguments, otherwise, the compiler will report an error. e.g. ABC obj1; //invalid will cause an error as no argument value has been supplied at the time of object declaration. Constructors can be invoked in two ways: 1. IMPLICITLY e.g ABC obj1(13,11.4,‘p’); Also known as shorthand method. 2. EXPLICITLY e.g ABC obj1= ABC(13,11.4,‘p’);

16 TEMPORARY INSTANCES The explicit call to the constructor also allows you to create a temporary instance or object. A temporary instance is the one that lives in the memory as long as it is being used or referenced in an expression and after this it dies. The temporary instances are anonymous i.e they do not bear a name. e.g sample obj1(2,5); //an object obj1 created obj1.print( ); sample(4,9).print( );

17 COPY CONSTRUCTOR sample s1; //default constructor used
sample s2=s1; //copy constructor used In the above code, for the second statement, compiler will copy the instance s1 to s2 member by member . If you have not defined a copy constructor, the compiler automatically, creates it and it is public. The process of initializing through copy constructor is known a copy initialization. You can create your copy constructor also.

18 class sample { int i , j ; public: sample (int a , int b) //constructor { i=a; j=b; } sample (sample & s) // copy constructor { j= s.j ; i=s.j ; cout<<“Copy constructor working”; } void print (void) { cout<<i<<j; } };

19 one parameterized and other copy constructor.
This code has two constructors: one parameterized and other copy constructor. These constructors may be used as: sample s1(4,a); sample s2(s1); //s1 copied to s2 sample s3=s1; //s1 copied to s3 But s4=s1; will not invoke the copy constructor. However, if s4 and s1 are objects of same type, this statement is valid and simply assigns values of s1 to s4,member by member.

20 CONSTRUCTOR OVERLOADING
Just like any other function, the constructor of a class may also be overloaded so that even with different number and types of initial values, an object may still be initialized. Overloaded member functions may be used to set or return values in a class. Example in C++

21 OVERLOADING vs DEFAULT ARGUMENTS
Advantages of function overloading over default arguments: Default arguments may not work for all possible combinations of arguments whereas a function may be overloaded for all possible combinations of arguments. With function overloading, multiple function definitions can be executed but with default arguments exactly one function is executed. By declaring an overloaded function, you save the compiler from the trouble of pushing the default argument value on the function call stack, and you save the function from the trouble of testing the default value.

22 DESTRUCTORS class sample { int i , j ; public:
A Destructor is also a member function whose name is the same as the class name but preceded by tilde (‘~’). e.g. class sample { int i , j ; public: sample (int a , int b) //constructor { i=a; j=b; } ~ sample( ) { cout<<“Destructor”; } }; int main( ) { sample s1(3,4); // automatically s1 is destructed at the end of the block using destructor ~ sample( ) }

23 CHARACTERISTICS OF DESTRUCTORS
Invoked automatically when objects are destroyed. You can have only one destructor in a class. i.e. Destructors can’t be overloaded. Each object of the class will be deinitialized before the object goes out of scope.( Local objects at the end of the block defining them and global objects at the end of the program. They also follow access rules. No argument can be provided to a destructor, neither does it return any value. They cannot be inherited. It is not possible to take the address of a destructor. Member functions may be called from within the destructor.

24 Assignment

25 Q1: What is copy constructor
Q1: What is copy constructor? Give an example in C++ to illustrate copy constructor. Q2: Differentiate between Constructor and Destructor function in context of classes and objects using C++. Q3:Answer the questions based on this Program: class retail { char category[20],item[20]; int qty; float price; retail( ) // Function 1 { strcpy (category, “Cereal”); strcpy (item, “rice”); qty=100; price=25; } public:

26 void show( ) // Function 2
{ cout<<category<<“-”<<item<<“:”<<qty << <<price<<endl; } }; void main( ) { retail r; // statement 1 r.show( ); // statement 2 Will statement 1 initialize all the data members for object r with the values given in the function 1? (Yes or NO). Justify your answer suggesting the correction's to be made in the above code. What will be the output ? (assuming corrections are made)

27 Q4: Define a class clothing in c++ with the following descriptions:
Private members: code of type string type of type string size of type integer material of type string price of type float A function calc_price( ) which calculates and assigns the value of price as follows: For the value of material as “COTTON”:

28 TYPE PRICE (Rs) trouser shirt For materials other than “COTTON” the above mentioned Price gets reduced by 25%. Public Members: A constructor to assign the initial values of code, type and material with the “NOT ASSIGNED” and size and price with 0. A function enter( ) to input the values of the data members code , type ,size and material to invoke the calc_price( ) function. A function show( ) which displays the content of all the data members for a clothing.

29 Q5: Describe the importance of destructor.
Q6: How many times is the copy constructor called in the following code? sample func (sample u) { sample v(u); sample w=v; return w; } void main( ) { sample x; sample y= func(x); sample z= func(y);


Download ppt "CONSTRUCTORS AND DESRUCTORS"

Similar presentations


Ads by Google