KEMBAR78
C++ - Unit 3 | PDF
0% found this document useful (0 votes)
4 views29 pages

C++ - Unit 3

The document provides an overview of constructors and destructors in C++, explaining their purpose, types, and characteristics. It details default, parameterized, and copy constructors, along with the syntax for defining them, and discusses the role of destructors in memory management. Additionally, it touches on operator overloading, including unary and binary operators, with examples illustrating their implementation.

Uploaded by

jaynthir01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

C++ - Unit 3

The document provides an overview of constructors and destructors in C++, explaining their purpose, types, and characteristics. It details default, parameterized, and copy constructors, along with the syntax for defining them, and discusses the role of destructors in memory management. Additionally, it touches on operator overloading, including unary and binary operators, with examples illustrating their implementation.

Uploaded by

jaynthir01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 29
5 Constructors and Destructor 9.1 Constructors sauhe main use of constructors is to initialize objects. The function of lization is automatically carried out by the use of a special member function called a constructor. Constructor is a special member function tha, takes the same name as the class name, The constructor is automatically calle when an object is created. ” The syntax generally is as given below: class ClassName { // private members Public: // public members ClassName( ) // constructor without parameters (i // body of the constructor he he 9.2 Types of Constructor There are several forms in which a constructor can take its shape, namely: ~ Default Constructor -© Parameterized Constructors © — Copy constructor 92.1 Default Constructor This constructor has no arguments in it. Default Constructor is also called no argument constructor. Example: class creature { private: int yearofBirth; public: creature () { cout<<“Contructor called"; } ee Constructors and Destructor Me int main() Uf 92 creature obj; getch(); return 0; ) 9.2.2 Parameterized Constructor A parameterized constructor is just one that has parameters specified in it. ‘We can pass the arguments to constructor function when objects are created. ‘Constructors that can take arguments are called parameterized constructors. Example ene Write a C++ program to implement parameterized constructor. #include #include class Test hf int a, b; public : Test ( int x, int y); // Constructor with two arguments Void show(); Me Test::Test (int x, int y) { cout <<”\n You are in the constructor ...”7 a=xib=y? } void Test::show() { cout<<”\n The values of a = “<< a << “ and b = “< ginclude class student { int no; char *name; public: student (int n, char *na) { no=n; name=new char (strlen (na) +1); name=na; iL void print () { cout<<”No="< class car { private: int speed; char color(20]7 public: car( ) //Constructor { cout<<"\nCreating a Car"; + ~car( ) //Destructor { cout<<"\nDestroying the Car"; } Me //End of class declaration int main( ) { car mine; return 0; } ‘The output of the above program, is shown here Creating a Car Destroying the Car Example 2 class creature { private: int yearofBirth; public: creature () { yearofBirth=1970; cout<<"constructure called"<> <<= 0s Be IE | Bitwise operator Increment/decrement ++ = operator : 10.1.1 Defining operator overloading ‘Overload can be defined inside the class or outside the class. If defined inside, the declaration and definition are same. If defined outside, it should b& vTocléed inside using prototype. The general form is Defining Inside the class To overk oad a operator, a operator function is defined inside a class as: return_tyPpe operator sign(argument list) _-0— ele Operator Overloading 10.2 ‘The return type comes first which is followed followed by operator sign,i.e., tin Operiit YH Gull Orereal Hei 2 7 atc., and finally the argument is passed. Then, inside the body of you wants perform the task you want when this operator function is called. This function is called i ctjos of at clas clase nae Seana Example #include class temp { private: int count; public: temp():count(5){ } void operator ++() qi count=count+1; } void Display() { cout<<"Count: "< #include class complex int a,b,c; Public: complex () {} void getvalue() >a>>b; } void operatort+() { a=tta; b=++b; } void operator--() { < a=--a; be--b; } void display () { cout< #include class ISC { int a,b; public: void get() { cout<<"Enter any two no.'s"; // to get the input from user cin>>a>>b; } ISC operator+(ISC d) // + operator is overloaded { 2 Isc f7 f.a=atd.a; £.b=b+d.b; return f; I void show() // to print the result { cout< #include class s { public: int i,j; void disp() { cout << i <<" " << 3; } void getdata() { cin>>i>>5; } friend s operator+(int,s) ; pie 8 operator+(int a, s sl) ft skp ij F Programming in C++ and Data Struct, at+sl.j; return kj; } int main() { 8 82; s2.getdata(); S$ s3 = 10+s2; S3.disp(); return 0; } First statement says that si and s2 are statement ‘+’ is a binary operator which ‘one operand 10 which is an integer object of class s. The statement s1=10+32; > 10.operator(s2). Here, left hand side ‘operand Function BT C8 Pe with that we cannot invoke the opening ore function. ee le thf Te hand side operand isnot an objet, then ve cannot i the operator function as a member function. So, this statement should be implemented as a friend function, friend s operator+int a, 8 sl) ~ since it isa friend i Operator. Because this Passed in the friend function, objects of class s. In the second takes two operands. In this ‘ype and another operand s2 which is ap function, we need to Pointer is not implicitly Operator Overloading 10.8 Example writes C+ program to manipulate a strings asing operators #include #include #include #include class string ; protected: char str[25}; public: void getstring(); void putstring (strings) ; void display(); string operator+(string&) ; void operator+=(string&) ; ie void string: :getstring() { cout<<"Enter string gets(str); } void string: :putstring(string &s) { int len=strlen(s.str); cout< class distance { int feet; | float inch; public: distance (float p) //costructor to concert basic type to class type feet= (int) pr | inch=(p-feet) *12; void show() { { cout<<"feet="< Class time { int hy int m; int 8; Public: time () { h=0; m=0; s=07 oc operator int() i pas int sl; s1=h*3600+minute*60+s; return (sl); } void display() Operator Overloading 10. 12 { cout<<"\n him: s="<>h>>m>>s; le void main() { time tl; int sec; tl.read(); tl.display(); sec=int (tl); cout<<”\n Total second of tl ="< int main() { int value; cout << "Value lives at " << 6value; cout << "\n\n"; return 0; } After executing the program, you could get: ‘Value lives at: 0x006SFDF4 Example 2 include int main({) { int value; int *pointer; cout << "Value lives at " << svalue << "\n"; cout << "Pointer lives at " << &pointer; cout << "\n\n"7 ~ return 0; } After executing the program, you might get: Value lives at: 0x006SFDF4 Pointer lives at: 0x0065FDFO Example 3 #include int main() { int value = 12; ,/ int *pointer = gvalue; ‘ cout << "Value lives at: " << value << "\n"; cout << "Pointer lives at: " << *pointer; cout << "\n\n"7 return 0; , The output of the above program is shown here: The program would produce: Value lives at: 12 Pointer lives at: 12 ae, Ss . ming in C++ and Data Structure 6.2 Arrays : Arrays are widely used data type in C++ language. Array is a group of related data items, that share a common name with same data type. An individual variable in the array is called an array element. aoe w arrayname, rollno to represent of oe . es of snudeots, A particular value is indicated by a number called index number. An index number is present in brackets after the arrayname. ‘There are mainly two types of Arrays are used: * One dimensional Array * Two dimensional Array « Multidimensional Array 6.2.1 One dimensional array A list of items group in a single variable name with only one index is called 1- D array. Declaration and initialization of arrays (@ Declaration of one array ‘We can declare an array in C using subscript operator. The general form isdatatype var_name[size]; i) int mark(50]; ; This declares an integer type array names as mark having 50 mem locations to store 100 integer data, 7 ii) float salary(30]; This declares a floating point type array named as having 30 metnory locations to store 30 floating point data. - iii) char name(20}; This declares a character type array named. as i memory locations to store 20 characters, oe (i) Initialization of 1-D arrays We can store values at the time of declaratio i , a mn. The comy the required space depen ng upon the list of values. The ened fe datatype array name(size] = { list of val a ai ues}; 4) int mark[4]=(45, 58,90, 76); is dec a lares mark as an inte having locations and assign initial values as given below, ee “ = Pointers and Arrays 6.4 ii) int mark[6); If the size of the array is great i : then the unused locations Sreater than the number of values in the list, Aare filled with zeros as given below mar(0] | mar{i} mark[2} | mark{3] | mark(4]_ | mark{5] 4s [se 9 | 6 0 0 iii) char dept[10); This declares name as a character array having 10 characters and assign initial values as eptO1 | dept] | dept} | dept3] ] depifa} | depts} | aepti6) | dept) Cc Oo P U T E R \o Example #include int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28); cout << "Distance 1: " << distance[0] << endl; cout << "Distance 2: " << distance[1] << endl; cout << "Distance 3: " << distance[2] << endl; cout << "Distance 4: " << distance[3] << endl; cout << "Distance 5: " << distance[4] << endl; return 0; awn } This would produce: Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 6.2.2 Two dimensional arrays A list of items group in a single variable name with two indexes (row and column size) is called 2-D array. - i) Creation of 2-D arrays ‘We can create two dimensional array as follows: datatype arrayname[sizel] [size2]; Here, . sizel —number of rows size2 —number of columns Frmmapile FJ Programming in C++ and Data Structure $$ This represents 2 too dimensional array named arr. Strnctiire cof twn-dimensiomal arrays as shown here: aioe) | exrfjtt) | arrf)(2] lene — eri anf H}2I + mark(5) (2)? ‘This declares mark as a two dimensional integer array having 5 rows and 2 columns. The total number of locations is 5x 2 = 10. columns column row0 | mark(0J[0] | mark(OJ[1] rowl | mark(1](0)__| mark{1](1] row2_| mark(2][0]__| mark{2][1] row3 | mark[3][0] _| mark(3][1] rows | mark[4}[0]__| mark(4]{1] ii) Initialization of 2-D arrays “Two dimensional aray can be initialized similar to one dimensional array as below. datatype arrayname[sizel].[size2]={list ofvalues}; Example i) int mark{3}[2]=(45,65,89, ,78,99,66};, mark[0}[0]_|_mark{O}[1] 45 65 mark(1}[0} | _mark(1)[1] 89 3 mark[2}[0]_|_ mark(2}{1] 99 66 Example 1 #include int main() _ { // A 2-Dimensional array double distance[2] [ 468.78, 4] = (44.14, 720.52, cout << “Members of the array"; f 96.08, 6.28, 68.04, 364.55, 6234.12}; // Scan the array from the 3rd to the 7th member Pointers and Arrays 6.6 cout << "\nDistance [0)[0)" <<": * cc distance [0] (0); cout << "\nDistance [0] [1}" <<": * cz distance[0] (1); cout << "\nDistance [0] [2]" <<": " cc distance(0) [2]; cout << "\nDistance (0](3]" <<": " cc distance [0] (3); cout << "\nDistance [1](0]" <<": " << distance(1] [0]; cout << "\nDistance (1) (1)" main() { int m, n, c, d, first[10][10], second[10} [10], sum[10] {10}; cout << "Enter the number of rows and columns of matrix "; cin >> m >> n; ee | } Programming in C++ and Data Structure irst trix\n"; nter the elements of first ma \ om << S for ( c*#0;ccem: ct) for (d= 0; d¢n7 dt) cin >> first{c] (d]* cout ce "Enter the elements of second matrix\n"; for (c=#=0; ¢> second[c] [d]; for (c=0;c¢ void main() 6.8 Pointers and Arrays ~~ { int i,je char achar[2] [2] = {'a','r','r','a'}; for (i=0;4<2; i++) { for (j=0;4<2;4++) i cout << "Row:: "<< i+] << "s column::"<< j+l <<" element is:: "<< achar[i] [j]<< "\n'? } } } The output of the above program is shown here. Row:: 1s column::1 element is :: A element is Row:: 2s column::1 element is Row:: 2s column::2 element is :: a In the above example, the character array "achar" is used to display elements of rows, columns using a loop. Summary A pointer is a variable which contains the address in memory of another variable. ¢ A pointer is a variable that contains the memory location another variable in which data is stored ¢ The address of a variable can be stored in another variable called the pointer variable © The address operator & gives the “address of a variable”. $ The indirection or dereference operator * gives the “contents an object pointed to by a pointer”. . Arrays are widely used data type in C++ language. Array is a group of related data items, that shares a common name with same data type + A list of items group in a single variable name with only index is called 1- D array ee en 2 ee, ae

You might also like