Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Constructors, Destructors, and Pointers in C++: A Comprehensive Guide, Study notes of Computer Science

A comprehensive guide to constructors, destructors, and pointers in c++. It covers the fundamental concepts, syntax, and examples of each topic. The document also explores the use of constructors for object initialization, destructors for object cleanup, and pointers for dynamic memory allocation and manipulation. It is a valuable resource for students and programmers learning c++.

Typology: Study notes

2023/2024

Available from 12/17/2024

myraa
myraa 🇮🇳

6 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Page | 1
Unit III
1. Constructors
Special member function which enables an object to initialize itself when it is created
Its name is same as the class name
Constructor definition outside class:
class integer
{ int m,n;
public:
integer(void);
……….
};
integer :: integer (void)
{ m=0; n=0;}
Constructor definition within class:
class integer
{ int m,n;
public:
integer(void)
{ m=0; n=0;}
……….
};
Characteristics of constructor:
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, and they cannot return
values
They cannot be inherited, though a derived class can call the base class
They can have default arguments
Constructors cannot be virtual functions
2. Parameterized Constructors
class integer
{ int m,n;
public:
integer (int x, int y);
……….
};
integer :: integer (int x, int y)
{
m=x;
n=y;
}
Explicit constructor call: integer int1=integer(1,2);
Implicit constructor call: integer int1(1,2);
3. Multiple Constructors in a Class
class code
{ int id;
public: code( ){ id=5;}
code (int a) { id=a; }
code( int a, int b) {id=a+b; }
};
In this class ‘code’ we have three constructors:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Constructors, Destructors, and Pointers in C++: A Comprehensive Guide and more Study notes Computer Science in PDF only on Docsity!

Unit III

1. Constructors

■ Special member function which enables an object to initialize itself when it is created ■ Its name is same as the class name ■ Constructor definition outside class: class integer { int m,n; public: integer(void); ………. }; integer :: integer (void) { m=0; n=0;} ■ Constructor definition within class: class integer { int m,n; public: integer(void) { m=0; n=0;} ………. }; Characteristics of constructor: ■ 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, and they cannot return values ■ They cannot be inherited, though a derived class can call the base class ■ They can have default arguments ■ Constructors cannot be virtual functions

2. Parameterized Constructors

class integer { int m,n; public: integer (int x, int y); ………. }; integer :: integer (int x, int y) { m=x; n=y; } ■ Explicit constructor call: integer int1=integer(1,2); ■ Implicit constructor call: integer int1(1,2);

3. Multiple Constructors in a Class

class code { int id; public: code( ){ id=5;} code (int a) { id=a; } code( int a, int b) {id=a+b; } }; In this class ‘code’ we have three constructors:

i) code(): This is a constructor with no parameters. ii) code(int a): This is a constructor with one parameter. iii) code(int a, int b): This is a constructor with two parameters. Hence, multiple constructors may be used in a class as shown in the above code.

4. Questions

Q.1) What is a constructor? Why is it used? Q.2) What are the rules for creating a constructor? Q.3) How can parameterized constructors be implemented in C++? Q.4) How can multiple constructors be implemented in C++?

5. Constructors with Default Arguments

class Demo { private: int X,Y; public: Demo() { X = 0; Y = 0; cout << endl << "Constructor Called"; } Demo(int X, int Y=20) { this->X = X; this->Y = Y; cout << endl << "Constructor Called"; } void putValues() { cout << endl << "Value of X : " << X; cout << endl << "Value of Y : " << Y << endl; } }; void main() { clrscr(); Demo d1= Demo(10); cout << endl <<"D1 Value Are : "; d1.putValues(); Demo d2= Demo(30,40); cout << endl <<"D2 Value Are : "; d2.putValues(); getch(); } Output: Constructor Called D1 Value Are : Value of X : 10 Value of Y : 20

void join(String &a, String &b); }; void String::join(String &a, String &b) { length=a.length+b.length; delete name; name=new char[length+1]; strcpy(name,a.name); strcpy(name,b.name); } void main() { char *first=“Ann ”; String name1(first),name2(“Ben “),name3(“Joy”),s1,s2; s1.join(name1,name2); s2.join(s1,name3); name1.display(); name2.display(); name3.display(); s1.display(); s2.display(); } OUTPUT: Ann Ben Joy Ann Ben Ann Ben Joy

9. Destructors

■ Member function used to destroy the objects that have been created by a constructor ~integer( ) { } ■ Never takes any argument ■ Never returns any value ■ Will be invoked implicitly by the compiler upon exit from the program/block/function ■ Example: class Demo { private: int X,Y; public: Demo() { X = 0; Y = 0; cout << endl << "Constructor Called"; } Demo(int X, int Y=20) { this->X = X; this->Y = Y; cout << endl << "Constructor Called"; } ~Demo() { cout << endl << "Destructor Called" << endl; } void putValues()

{ cout << endl << "Value of X : " << X; cout << endl << "Value of Y : " << Y << endl; } }; void main() { clrscr(); Demo d1= Demo(10); cout << endl <<"D1 Value Are : "; d1.putValues(); Demo d2= Demo(30,40); cout << endl <<"D2 Value Are : "; d2.putValues(); getch(); } Output: Constructor Called D1 Value Are : Value of X : 10 Value of Y : 20 Constructor Called D2 Value Are : Value of X : 30 Value of Y : 40 Destructor Called Destructor Called

10. Questions

Q.1) How can constructors with default arguments be implemented in C++? Q.2) How can objects be dynamically initialized? Q.3) What is a Copy Constructor? Why is it used? Q.4) What is a Dynamic Constructor? Why is it used? Q.5) What are destructors? How can they be used in C++?

11. Pointers

Pointers are variable that holds a memory address. & indicates Address of

  • indicates Value at address Consider the following C++ code: int i=3, j,k; j=&i; k=&j; The variable i stores value 3, pointer j stores the address of i and double pointer k stores the address of pointer j as shown in the figure. The system evaluates: k=(&j)= &j= k= k=(&j)=(&i)=
  • A pointer can be incremented or decremented
  • Any integer can be added or subtracted from a pointer
  • One pointer can be subtracted from another

Stream I/O Library Header Files ■ iostream -- contains basic information required for all stream I/O operations ■ iomanip -- contains information useful for performing formatted I/O with parameterized stream manipulators ■ fstream -- contains information for performing file I/O operations ■ strstream -- contains information for performing in-memory I/O operations (i.e., into or from strings in memory)

15. C++ Stream Classes

■ ios is the base class. ■ istream and ostream inherit from ios ■ ifstream inherits from istream (and ios) ■ ofstream inherits from ostream (and ios) ■ iostream inherits from istream and ostream (& ios) ■ fstream inherits from ifstream, iostream, and ofstream C++ Stream I/O -- Stream Manipulators ■ C++ provides various stream manipulators that perform formatting tasks. ■ Stream manipulators are defined in ■ These manipulators provide capabilities for

  • setting field widths
  • setting precision
  • setting and unsetting format flags
  • flushing streams
  • inserting a "newline" and flushing output stream
  • skipping whitespace in input stream setprecision ( ) ■ Select output precision, i.e., number of significant digits to be printed. ■ Example: cout << setprecision (2) ; // two significant digits setw ( ) ■ Specify the field width (Can be used on input or output, but only applies to next insertion or extraction). ■ Example: cout << setw (4) ; // field is four positions wide I/O Stream Member Functions .setf ( ) ■ Allows the setting of an I/O stream format flag. ■ Examples: // To show the + sign in front of positive numbers cout.setf (ios::showpos) ;

// To output the number in hexadecimal cout.setf (ios::hex, ios::basefield) ; .precision ( ) ; ■ Select output precision, i.e., number of significant digits to be printed. ■ Example: cout.precision (2) ; // two significant digits .width ( ) ; ■ Specify field width. (Can be used on input or output, but only applies to next insertion or extraction). ■ Example: cout.width (4) ; // field is four positions wide .eof ( ) ; ■ Tests for end-of-file condition. ■ Example: cin.eof ( ) ; // true if eof encountered .fail ( ) ; ■ Tests if a stream operation has failed. ■ Example: cin.fail ( ) ; // true if a format error occurred ! cin; // same as above; true if format error .clear ( ) ; ■ Normally used to restore a stream's state to "good" so that I/O may proceed or resume on that stream. ■ Example: cin.clear ( ) ; // allow I/O to resume File I/O with C++ #include <fstream.h> void main ( ) { int a, b, c ; ifstream fin ; //Create file input stream object fin.open ( "my_input.dat") ; //Open input file fin >> a >> b ; //Read two values from input file c = a + b ; ofstream fout ; //Create file output stream object fout.open ( "my_output.dat"); //Open output file fout << c << endl ; //Write result to output file fin.close ( ) ; //Close input file fout.close ( ) ; //Close output file }

16. Questions

Q.1) What is a pointer? Q.2) How can pointers be used with arrays? Q.3) What are C++ Streams? Q.4) What are the various stream classes used in C++? Q.5) Explain the various I/O stream member functions. Q.6) How can you use streams for file handling?

17. Unformatted I/O Operation

  • Unformatted console input/output functions are used for performing input/output operations at console and the resulting data is left unformatted and untransformed i.e. it is left in its raw and original form.

cout << "Enter your name" << endl ; cin.getline (name, 30) ; cout << "Enter two integers and a float " << endl ; cin >> a >> b >> k ; cout << "\nThank you, " << name << ", you entered" << endl << a << ", " << b << ", and " ; cout.width (4) ; cout.precision (2) ; cout << k << endl ; // Control the field and precision another way cout <<"\nThank you, " << name << ", you entered"<< endl << a << ", " << b << ", and " << setw (c) << setprecision (d) << k << endl ; getch(); } Output: Enter your name Amar Enter two integers and a float 4 4

Thank you, Amar, you entered 4, 4, and 6. Thank you, Amar, you entered 4,4, and 6.

20. Questions

Q.1) How can you use functions for unformatted I/O Operations? Q.2) How can you use functions for formatted I/O Operations? Q.3) What are Manipulators? Q.4) Write a C++ program to use manipulators for managing outputs on the console.

21. Exception

An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.

  • throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
  • catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
  • try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows − try { // protected code } catch( ExceptionName e1 ) {

// catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block } You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.

22. Exception Handling

■ Find the problem (Hit the exception) ■ Inform that an error has occurred (Throw the exception) ■ Receive the error information (Catch the exception) ■ Take corrective actions (Handle the exception) Exception Handling Mechanism is depicted below: Example: #include <iostream.h> void main() { int x = - 1; // Some code cout << "Before try \n"; try { cout << "Inside try \n"; if (x < 0) { throw x; cout << "After throw (Never executed) \n"; } } catch (int x ) { cout << "Exception Caught \n"; } cout << "After catch (Will be executed) \n"; } Output: Before try Inside try Exception Caught After catch (Will be executed) try block Detects and throws an exception catch block Catches and handles an exception Exception Object

Because we are raising an exception of type const char* , so while catching this exception, we have to use const char* in catch block. If we compile and run above code, this would produce the following result − Division by zero condition!

25. C++ Standard Exceptions

C++ provides a list of standard exceptions defined in which we can use in our programs. These are arranged in a parent-child class hierarchy shown below − Here is the small description of each exception mentioned in the above hierarchy: S.No Exception & Description 1 std::exception An exception and parent class of all the standard C++ exceptions. 2 std::bad_alloc This can be thrown by new. 3 std::bad_cast This can be thrown by dynamic_cast. 4 std::bad_exception This is useful device to handle unexpected exceptions in a C++ program. 5 std::bad_typeid This can be thrown by typeid. 6 std::logic_error An exception that theoretically can be detected by reading the code.

7 std::domain_error This is an exception thrown when a mathematically invalid domain is used. 8 std::invalid_argument This is thrown due to invalid arguments. 9 std::length_error This is thrown when a too big std::string is created. 10 std::out_of_range This can be thrown by the 'at' method, for example a std::vector and std::bitset<>::operator. 11 std::runtime_error An exception that theoretically cannot be detected by reading the code. 12 std::overflow_error This is thrown if a mathematical overflow occurs. 13 std::range_error This is occurred when you try to store a value which is out of range. 14 std::underflow_error This is thrown if a mathematical underflow occurs.

26. Defining New Exceptions

You can define your own exceptions by inheriting and overriding exception class functionality. Following is the example, which shows how you can use std::exception class to implement your own exception in standard way − #include #include using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } }; int main() { try { throw MyException(); } catch(MyException& e) { std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl; } catch(std::exception& e) { //Other errors } } This would produce the following result −