1 / 114

Unit-VI

Unit-VI. Constructors-default constructor parameterized constructor constructor initialization list copy constructor Destructors Static class members this pointer friend functions and classes Dynamic memory management with operators new and delete. Overloading-functions.

heller
Download Presentation

Unit-VI

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit-VI • Constructors-default constructor • parameterized constructor • constructor initialization list • copy constructor • Destructors • Static class members • this pointer • friend functions and classes • Dynamic memory management with operators new and delete. • Overloading-functions. • overloading Operator overloading • restrictions on operator overloading. • overloading unary and binary operators. • type conversion. • Templates. • Inheritance.

  2. void main() { test t; t.display(10,20); } class test { int a,b; public: void display(int x,int y) { a=x; b=y; cout<<“a=“<<a’; cout<<“b=“<<b; } }; When object t created, it is not initializing the data members of class. It is performed by a call to the function display Display function cannot initialize its members when the object created.

  3. constructors • A constructor is a special member function whose task is to initialize the objects of its class when they are created. This is also known as automatic initialization of objects. • It is special because its name is the same as the class name • The constructor is executed automatically whenever an object of its associated class is created • It is called constructor because it constructs the values of data members of the class. • The constructor is executed every time an object of that class is created.

  4. Syntax for class with a constructor: class classname { //private members public: classname(); //constructor declaration ---------- ---------- }; classname :: classname (void) //constructor definition { } The constructor is invoked automatically when the objects of that class are created . No need to write the special statement.

  5. Example of constructor • Class test { int a,b; test(int x,int y); }; test::test(int x,int y) { a=x; b=y; cout<<“a=“<<a’; cout<<“b=“<<b; } void main() { test t(10,20); test s(40,50); } output a=10 b=20 a=40 b=50

  6. Characteristics of constructors • Constructor name is same as class name. • 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. • Constructor can access any data members but cannot be invoked explicitly. • They cannot be inherited, through a derived class can call the base class constructor • Like other , they can have default arguments • They make ‘implicit calls’ to the operators new and delete when memory allocation is required • Note: when a constructor is declared for a class, initialization of the class objects become mandatory

  7. Types of constructors -There are three types of constructors 1) Default constructor 2) Parameterized constructor 3) Copy constructor

  8. Default constructor -constructor without arguments\ parameters is called default constructor. - default constructor name is same as class name. - default constructor does not include return-type, not even void. - default constructor does not return any value. - default constructor is invoked implicitly after creation of the objects (no need to invoke explicitly).

  9. example Void main() { test t1; cout<<“\n main”; func(); }//main Output constructor called. main constructor called. func() • Class test { public: test(); }; test :: test() { cout<<“constructor called”; } void func() { test t2; cout<<“func()”; }

  10. 2.Parameterized constructor • constructor which takes parameters is called Parameterized constructor. -Parameterized Constructor name is same as class name. -Parameterized Constructor does not include return-type, not even void. -Parameterized Constructor does not return any value. -Parameterized Constructor is invoked implicitly with parameters after creation of the object (no need to invoke explicitly). ex: class test { int m, n; public: test (int x, int y); // parameterized constructor ---------- ---------- }; test :: test (int x, int y) { m=x; n=y; } test t1;// it wont work. When the constructor is parametirized, we must provide appropriate arguments for the constructor.

  11. We must pass some initial values as arguments to the constructor when an object is created. • This can be done in two ways. 1. explicitly. 2. implicitly. 1. test t1= test(10,20);// explicitly 2. test t1(20,30);// implicit call.

  12. #include<iostream.h> Class integer { int m,n; public: integer(int,int); void display( ) { cout<<“m=“<<m<<“\n”; cout<<“n=“<<n<<“\n”; }//display() };//class Integer:: integer(int x,int y) { m=x; n=y; } main(){ integer I1(0,100); // constructor called implicitly integer I2= integer(10,20);// constructor called explicitly cout<<“\n object1”<<“\n”; I1.display(); Cout<<“\nobject2”<<“\n”; I2.display(); return 0; }//main

  13. Copy constructor - Constructor can also accepts the address of its own class as an argument. In such case the constructor is called copy constructor. -Copy constructor is a member function which is used to initialize an object from another object. -Copy Constructor name is same as class name. -Copy Constructor takes one parameter that is object. -Copy Constructor does not include return-type, not even void. -Copy Constructor does not return any value. -Copy Constructor is invoked implicitly with object as parameter after creation of the object (no need to invoke explicitly).

  14. Ex- class A { public: A(&A); };

  15. #include<iostream.h> class point { int a; public: point( ) //Default constructor { a=1000; } point(int x) //Parameterized constructor { a = x; } point(point &p) //Copy constructor { //p is an alternative name (alias) of object p1 a = p.a; } void display( ) { cout<<endl<<”a value is “<<a; } }; void main( ) { point p1; point p2(500); point p3(p1); p1.display(); p2.display(); p3.display(); }

  16. Destructor -Destructor is a member function which is used to destroy an object when an object is no longer needed. -Destructor name is same as class name preceded by tilde mark (~). -Destructor does not include return-type, not even void. -Destructor does not return any value. • Destructor cannot be overloaded. - Single destructor is used in a class without arguments. -Destructor is invoked when the object goes out of the scope. • If no user-defined destructor exists for a class, the compiler implicitly declares a destructor. • Ex: class X { public: X(); // Constructor for class X ~X(); // Destructor for class X };

  17. include<iostream.h> class test { public: test( ); //Default constructor ~ test(); }; test:: test() { cout<<“\n constructor of a class”; } test :: ~test() { cout<<“\n destructor of a class”; } void main( ) { test T; //constructor is invoked after creation of object p cout<<“\n main(); }// object T goes out of the scope, destructor is called.

  18. Example for no of objects created and alive. { cout <<“\n block1”; test t5; }//out of scope { cout<<“\n block2”; test t6; }// out of scope cout<<“\n re – enter main”; }//main int count=0; class test { public:n test() { count++; cout<<“no of objects created\n”<<count; } ~test() { cout<<“\n no of objects destroyed”<<count; count--; } Void main() { cout<<“\n main”; test t1,t2,t3,t4;

  19. Over loaded constructors • over loading means same thing is used for different purposes. • ex- computer. • When more than one constructor function is defined in a class, we can say that constructor is overloaded. • all the constructors have the same name as its corresponding class. However, they differ in their signature ( No. of arguments, data types of their arguments or both)

  20. test ( int x, int y)// constructor 3 { a=x; b=y; c=60; } void display() { cout<<ä=“<<a<<“\n”; cout<< “b=“<<b<<“\n”; cout<< “c=“<<c<<“\n “; } }; Int main() { test t1;//constructor1 test t2(10,20,30);// constructor 2 test t3(40,50);// constructor 3 t1. display(); t2.display(); t3.display(); Return 0;} Class test { private: int a,b,c; public: test()// constructor1 { cout<<“\n enter a ,b,c “; cin >>a>>b>>c; } // constructor 2 test(int x,int y,int z) { a=x; b=y; c=z }

  21. Static class members In some situations, we need to have one or more data which are accessible to all objects of the class. Syntax class class name { static data type data member; ……… }; data type class name:: data member=initial values; Note:- static data members should be declared inside the class and its definition out side the class. Initialization is optional

  22. Characteristics of static data members: • The variable which is declared as static is initialized to zero when the first object of its class is created. No other initialization is possible. • The static data members should be initialized during their definition out side all the member functions. • Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created • It is visible only within the class, but its lifetime is the entire program. • Public static data members accessed through scope resolution operator or through objects.

  23. example • Class test { public: static int a; private: static int b; }; Void main() { test:: a=12; test::b=19;// wrong test t; t.a=18; t.b=90;// wrong.

  24. int main() { item x,y,z; clrscr();x.getcount();->0 //y.getcount();->0 //z.getcount();->0 x.getdata(100); //y.getdata(200); //z.getdata(300); x.getcount();->3 //y.getcount();->3 //z.getcount();->3 getch(); return 0;} #include<iostream.h> #include<conio.h> class item { static int count; int number; public: void getdata(int a) { number=a; count++; } void getcount(void) { cout<<"count:"<<count; } }; int item :: count; Omit this statement out get linker error

  25. Note:- the scope and type of the static variable is defined separately outside of the class. This is necessary because the static data members are stored separately rather than as a part of object.

  26. Static member function Syntax static return_type functionname(arglist); ex static void displaly(); Characteristics of static member function: • A static function can have access to only other static members (data or functions) declared in the same class. • Non static data cannot be access to the static member functions. • A static member function can be called using the class name (instead of its objects) as follows class-name :: function-name;

  27. Class test { static int a; int b; public: static void display() { cout<<“a=“<<a;// correct cout<<“b=“<<b;// wrong- since static member function can access to static members. };

  28. int main() { test t1,t2; t1. setdata(); t2.setdata(); test :: showcount(); test t3; t3.setdata(); test ::showcount(); t1.showdata();1 t2.showdata();2 t3.showdata();3 return 0; } #include<iostream.h> #include<conio.h> class test { int x; static int count; public: void setdata(void) { x=++count; } void showdata(void) { cout<<"object number:"<<x<<"\n"; } static void showcount(void) { cout<<"count:"<<count<<"\n"; } }; int test :: count;

  29. Example program #include<iostream.h> class test { private: int a; public: void setdata(int x) { a=x;// normal way to set data cout<<“address of my object”<<this; this->a=x;// another way to set data } void showdata() { cout<<“\n address of object for showdata()”<<this; cout<<“a=“<<a; cout<<“ this->a”<<this->a; } void main() { test t,s; t.setdata(30); t.showdata(); s.setdata(40); s.showdata(); } this pointer -this pointer is a pointer which points to the currently invoked object. -this pointer can be used inside the member functions only. The member function of a class always with the pointer called this, which points to the object with which the function is invoked.

  30. #include<iostream.h> #include<conio.h> class test { int x,y,z; public: test(int x ,int y) { this->x=x; this->y=y; } void display() { cout<<“X:"<<x<<“Y:”<<y; } }; int main() { clrscr(); test t(10,20); t.display(); return 0; } Output: X:10 y:20

  31. #include<iostream.h> #include<string.h> class person { int age; char * name; public: person(){}; person(char* p, int i ) { strcpy(name ,p) ; age = i;} person greater(person x) { if (x.age>=age) return x; else return *this; } void display() { cout<<endl<<"Age is "<<age; cout<<endl<<"Name is "<<name; } }; void main() { clrscr(); person a ("ram" ,30), b("sam" , 35); person p; p=a.greater(b); //currently invoking object is a p.display(); a.display(); }

  32. friend functions and classes • Private and protected members of a class cannot be accessible to out side the class. The non member functions cannot have an access to these data of a class. • When two classes need to access the same function- make such function to be friend to both the classes. • Allow the function to have access to the private members of these two classes. • Such a function need not be member of any of these classes.

  33. Friend functions • Allow the non-member function to access even the private members of a class using the friend function or friend classes. • Friend functions are used to access private members of a class • syntax class classname { ….. ….. public: friend returntype functionname(object arg); }; • Function should preceded by keyword friend • The function is defined any where in the program • Function definition need not required any scope • resolution operator. • 4. Its not a member function of the class.however, • access to private members of a class.

  34. Characteristics of friend function • Function name is preceded by the keyword friend. • The scope of the friend is not limited to the class in which it has been declared. • Since it is not in the scope of the class, It cannot be invoked using the object of that class. • Invoked like a normal function. • It can be declared either in the public or the private part of a class. • It takes object as an argument. • Unlike the member functions, it cannot access the class members directly. However, it can use the object and dot operator with each member name to access both the private and public data.

  35. Example on ff Class xyz;// advanced class declaration class abc { private: int a; public: void setdata(int x) { a=x; } friend int add( abc ab,xyz xy); }; Class xyz; { private: int b; public: void setdata(int y) { b=y; } friend int add( abc ab,xyz xy); }; int add( abc ab, xyz xy) { return ab.a+xy.b; }// a and b are private void main() { abc ab; xyz xy; ab.setdata(10); xy.setdata(20); cout<<“sum of the two no=“ <<add(ab,xy); }

  36. Friend class • Whenever all the functions of one class can have access to the private members of the another class. • It is possible to make the entire class as a friend of another class. So that all the members of the friend class can have access to the private members of the another class.

  37. Syntax class A { …….. ……………….. friend class B; }; Class B { ……… ………. }

  38. Example on friend class void main() { ABC ab(10,20); XYZ xy;//object of XYZ xy.display(ab); } class ABC { private: int a,b; public: ABC(int x,int y) { a=x; b=y; } // make a class XYZ as friend class to ABC friend class XYZ; }; class XYZ{ public: void display( ABC ab){ cout<<“\n a in ABC class=“<<ab.a; cout<<“\n b in ABC class=“<<ab.b; } }; Display is function of friend class so that pass class object as argument

  39. Dynamic memory management operators new and delete. • Dynamic memory allocation- the requested memory allocated during run time of the program • Dynamic memory allocation used when the amount of memory required is not known in advance. • In c, we have used malloc() and calloc() functions and free() for de allocating the memory. • In c++, we can use two unary operators like new and delete. • They perform allocating and freeing the memory. They are also called free store operators. • An object can be created using the new and destroyed using the delete.

  40. New operator. • New operator allocates the memory dynamically similar to the standard library function malloc(). general form pointer variable=new datatype; • Pointer variable is a pointer of type datatype • - new operator allocates sufficient memory to hold an object of type data type and return the address of the object. • Example • int *p; • p=new int; • float *q; • q=new float; We can also combine the declaration and assignment like- int *p=new int; float *q= new float;

  41. We can initialize the memory using new operator int *p= new int(30); float *q=new float(10.5); • New can be used to create a memory dynamically for any data type like arrays, classes. • General form is Ex- int *p= new int[10]; Pointer- variable= new datatype[size];

  42. New operator • An object is created using new,and destroyed by using delete, as and when required. • Any object created with the new within a block, will remain exist until it is destroyed by using the delete operator. • Hence, the life time of object is under the control of programmer. • If requested memory is not available in the memory pool, new operator returns null pointer.

  43. Delete operator • Object created with new is no longer needed, it must be destroyed with the operator delete to release the memory for the reuse. • general form delete pointer variable; delete p; delete q;

  44. Example on new and delete • #include<iostream.h> int main() { char *name; name=new char[]; cout<<“enter the name”; cin>>name; cout<<name; delete [ ] name; return 0; }

  45. Create objects using new class ABC { int a,b; public: ABC(int x,int y) { a=x; b=y; } void display() { cout<<"\n a value is="<<a; cout<<"\n b value is="<<b; } };//class int main() { ABC *ab=new ABC(10,20); ab->display(); delete ab; return 0; }//main

  46. Compile-time polymorphism -Binding of a function call to the function definition at compile time is called compile-time polymorphism. -This is also called static binding or early binding. -Function overloading and operator overloading come under compile-time polymorphism.

  47. Function overloading • Function overloading- The process of two or more functions having same name and different in their signature( no. of arguments, type of arguments). • However, the overloading function differ only in their return type is not allowed.

  48. Use of function overloading • -> Function overloading is one of the most powerful features of C++ programming language. It forms the basis of polymorphism (compile-time polymorphism). • Most of the time you’ll be overloading the constructor of a class.

  49. Swapping of two numbers void swap_float(float a, float b) { float temp; temp=a; a=b; b=temp; } void swap_int(int a,int b) { int temp; temp=a; a=b; b=temp; }

  50. Overloading Functions that differ in terms of no of arguments #include<iostream.h> //FUNTION PROTOTYPES int func(int i); int func(int i, int j); int main() { cout<<func(10);//func(int i)is called cout<<func(10,10);//func(int i, int j) is called return 0; } int func(int i) { return i; } int func(int i, int j) { return i+j; }

More Related