









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
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
1 / 15
This page cannot be seen from the preview
Don't miss anything!
■ 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
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);
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.
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++?
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
■ 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
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++?
Pointers are variable that holds a memory address. & indicates Address of
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)
■ 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
// 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 }
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?
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.
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.
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.
// 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.
■ 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!
C++ provides a list of standard exceptions defined in
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.
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