Download presentation
Presentation is loading. Please wait.
Published byColin Rodgers Modified over 9 years ago
2
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND
3
Class Structure of a Class Constructor Types of Constructor Default Constructor Parameterized Constructor Destructor An example Conclusion
4
A class is a group of objects that share common properties and relationships. Class is a structure for implementing real world objects using any object based or object oriented programming language. Class creates only the definition for objects. Class is the combination of data members (characteristics) and member functions (behaviors) for the object.
5
class Student { private: int AdmNo, RollNo; char Name[30], ClassName; public: void InsertData(void); void ShowData(void); } S1, S2; Keyword Name of the Class Access Specifiers Data Members Object ListMember Functions
6
Constructors A constructor is a special member function with the same name as its class name. It is called constructor because it constructs the values of data members of the class. The constructor is invoked whenever an object of its associated class is created. It invokes automatically by the C++ compiler, when an object is created. Use- It is used to initialize the object of the class type with a legal initial value.
7
class add { int m, n ; public : add (void) ; ------ }; add :: add (void) { m = 0; n = 0; } When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically. add a ; Not only creates the object a of type add but also initializes its data members m and n to zero.
8
There is no need to write any statement to invoke the constructor function. If a ‘normal’ member function is defined for zero initialization, we would need to invoke this function for each of the objects separately. A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A : : A ( ) continue …
9
They are invoked automatically when the objects are created. All the objects of the class having a constructor are initialized before some use. These should be declared in the public section for availability to all the functions They do not have return types, not even void and they cannot return values. They cannot be inherited, though a derived class can call the base class constructor.
10
We can not refer to their addresses. An object with a constructor (or destructor) can not be used as a member of a union. They make ‘implicit calls’ to the operators new and delete when memory allocation is required. When a constructor is declared for a class initialization of the class objects becomes mandatory. Like other C++ functions, Constructors can have default arguments. Constructors can not be virtual.
11
1. These cannot be static. 2. Default and copy constructor are generated by the compiler whenever required. Generated constructors are public. 3. Constructors can have default argument as other C++ functions. 4. A constructor can be used explicitly to create new objects it class type, using the syntax Class-name(expression-list) 1. Sample obj1=Sample(13,22.42);
12
Constructor may be of following types: Default constructor User defined constructor Parameterized construc tor Copy Constructor
13
It is also created by the user but it has some values that can be passed for initializing the data members. This is achieved by passing arguments to the constructor function when the objects are created. Parameter values are passed from the caller function with the object followed by the parentheses. The constructors that can take arguments are called parameterized constructors.
14
The syntax is: ( ) { // Data members values // Initialization statements } For parameterized constructor (parameter list) { // Data members values // Initialization statements }
15
class add { int m, n ; public : add (int, int) ; ------ }; add : : add (int x, int y) { m = x; n = y; } moid main() { add sum(100,200); } When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared. Two ways Calling: o Explicit add sum = add(2,3); o Implicit add sum(2,3) Shorthand method
16
When there is no any constructor defined in the class by the user, then this constructor is used. It is invoked by the C++ compiler for creating the space for data members and the compiler fills data members with garbage values. A constructor that accept no parameter is called the default constructor. You can’t create an array of objects unless your class has a default constructor( implicitly or explicitly defined)
17
class Test{ int a;char b; Public: Test(int I,char j) {a=I;j=b; } }; void main() { Test Tarray[5]; //wrong Test newobj(31,’z’); //ok } class Test{ int a;char b; Public: Test(){ cout<<“Default constructor \n”;} Test(int I,char j) {a=I;j=b; cout<<“parameterized constructor \n”; } }; void main() {Test Tarray[5]; Test newobj(31,’z’); }
18
Temporary Instances The explicit call to a constructor also allows you to create a temporary instance or temporary 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.
19
class Sample{ int i,j; public:Sample(int a,int b) {i=a;j=b;} void print(voit){ cout<<i<<j<<“\n”; } }; void test(void) { Sample S1(2,5); S1.print(); Sample(4,9).print();//data values of atemporary.
20
It is a member function which initializes an object using another object of the same class If you have not defined a copy constructor, the complier automatically creates it and it is public Copy constructor always takes argument as a reference object. We cannot pass the argument by value to a copy constructor. A copy constructor has the following general function prototype: class_name (const class_name&); Consider the following class definition
21
class sample { int i, j; public: sample ( int a, int b) { i = a; j = b; } sample ( sample & s) { i = s.i ; j = s.j ; } void print(void) { cout<<i <<“ “<<j <<“\n”; } Above constructors may be used as follows sample s1 (10,12); //1 st const. called sample s2 (s1) // copy const. called sample s3 = s1; copy const. called
22
=> When is a copy constructor called? 1. When an object is passed by a value: The copy constructor is invoked when an object is passed by values to a function. the pass-by value method requires a copy of the passed argument to be created for the function to operate upon. void afunc(Sample); //Sample is a class afunc(obj1); // Obj1 is an object of Sample type. 2. When a function return an object: Sample afun( ); //prototype Obj2=afun( );//copy constructor invoked
23
Q. Why the argument to a copy constructor is passed by reference ? Order of Constructor Invocation The objects are constructed in the order they are defined. Consider the following statement Sample s1,s2,s3; // the order of construction is s1,s2,s3. But when a class containing objects of another class as its members. In such a case, the constructor for member objects are invoked first and then only, the constructor for containing class is invoked. For example
24
class A { public: A() { cout<<“Constructing A” <<endl; }}; class B { public: B() { cout<<“Constructing B” <<endl; }}; class C { private: A objA; B objB; public: C() { cout<<“Constructing C” <<endl; }}; int main() { clrscr(); C objC; getch(); }
25
Providing initial value to objects at run time. See the text book example:5.2.9 Advantage – We can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different format of data at run time depending upon the situation.
26
Same as member functions ovelaoding
27
=>A destructor has the same name as the class but is preceded by a tilde (~) => It is used to de-allocate or free the memory used by the object. It is better to include a destructor for a class. A destructor has normally no function body. ~ integer ( ) { } A destructor should be defined under the public sector of a class. so that its objects can be (used and then ) destroyed in any function
28
A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program – or block or function as the case may be – to clean up storage that is no longer accessible. It is a good practice to declare destructors in a program since it releases memory space for further use. Whenever new is used to allocate memory in the constructor, we should use delete to free that memory.
29
The syntax for creating a destructor is: ~ ( ) { } Tilde symbol indicating that a destructor is defined here.
30
class Book { private: int NoOfPages, Volume; char Name[30], Author[30], Publisher[30]; public: //Constructor Book ( ) { NoOfPages=100; Volume=1; } //Parameterized Constructor Book (int NP, int Vol) { NoOfPages=NP; Volume=Vol; } // Destructor ~Book ( ) { } void GetShowBookData( ); };
31
=>A destructor function is called automatically when the object goes out of scope(destroyed): (1) the function ends (2) the program ends (3) a block containing temporary variables ends (4) a delete operator is called => Only one destructor for a class. in other word, destructors can’t be overloaded. => If a class has a destructor, each object of the class will be de-initialized before the object goes out of scope(Local objects at the end of the block defining them and global and static object at the end of the program). => no arguments and return no values. => It can’t be inherited => A destructor may not be static.
32
=>It is not possible to take the address of a destructor. => Member functions may be called from within a destructor. => An object of a class with a destructor cannot be a member union. =>If you do not specify a destructor, the compiler generates a default destructor for you.
33
Constructor and destructor are special functions. They are used to allocate and de-allocate memory for objects. They are called special functions because they share common name between the class and themselves. Constructor and Destructor are always created in the public area of a class. They can also be used at the time of inheritance.
34
END
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.