C++ tutorial assignment - 23MTS5730.pptx

sp1312004 19 views 24 slides Oct 10, 2024
Slide 1
Slide 1 of 24
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24

About This Presentation

This C++ PowerPoint presentation stands out for its clear and concise explanation of complex concepts, making it accessible to both beginners and advanced programmers. The structured flow from basic syntax to more advanced topics like object-oriented programming and memory management showcases a dee...


Slide Content

PROGRAMMING FUNDAMENTALS USING C++ ASSIGNMENT NAME :- SAHIL PATEL ROLL NO :- 23MTS5730

UNIT 3 OBJECT ORIENTED PROGRAMMING

Call by re f erence   A reference refers to an alias or an alternate name for a variable. When an argument is passed by  reference an alias or a reference of the actual is passed to the formal argument.  In call by reference, a reference to an argument is created by suffixing the reference  operator or ampersand (&) to the data type of an argument in both the function definition and  declaration.   The syntax for declaring a function with reference type parameter is  return_type function_name(data_type &identifier)  The call by reference mechanism requires no overhead of creating copies of arguments in the  function and hence, and it makes the execution faster and it reduces memory utilization. It is  efficient to use call by reference mechanism when the argument occupies a lot of memory space  and copying the argument is not feasible.  Return by reference   Returning reference is useful in those situations when the function call is to be an Lvalue . An  Lvalue is an expression that appear on the left hand side of an equals to sign. In other words a  function returning a reference can be placed on left hand side of the assignment statement. To  return a reference , the reference operator (&) is suffixed to the return type in the function  prototype and definition. The following statement shows the return by reference  char &change(int i); 

Inline function   I nline function is a function whose body is copied and replaced with the function call statement whenever it is invoked. The keyword inline is used before the function name to make  it inline. It is an optimization technique used by the compilers as it saves time in switching  between the functions otherwise. Member functions of a class are inline by default even if the  keyword inline is not used.  Syntax of inline Function  inline return_type function_name ([argument list]) {   body of function  }  Inline function is suitable for small functions only. In case of large functions, it increases the  execution time slowing down the performance. Also, the code size increases reasonably when a  large function is called many times since the calling statement is replaced by the body of  function every time. So, in case of large functions, the compiler ignores the programmers request  to make a function inline even if the keyword inline is used.     Abstract data type   An abstract data type (or ADT) is a class that has a defined set of operations and values. In  programming, an ADT has the following features:  ∙ An ADT doesn't state how data is organized, and  ∙ It provides only what's needed to execute its operations  An ADT is a prime example of how you can make full use of data abstraction and data hiding.  This means that an abstract data type is a huge component of object-oriented programming  methodologies: enforcing abstraction, allowing data hiding (protecting information from other  parts of the program), and encapsulation (combining elements into a single unit, such as a class ).

Class   A class is a user-defined data type, which holds its own data members and member functions,  which can be accessed and used by creating an instance of that class. It is building block, that  leads to Object-Oriented programming.. A C++ class is like a blueprint for an object.  A Class is a user defined data-type which has data members and member functions. ∙ Data members are the data variables and member functions are the functions used to  manipulate these variables and together these data members and member functions defines  the properties and behavior of the objects in a Class.  A class is defined in C++ using keyword class followed by the name of class. The body of class  is defined inside the curly brackets and terminated by a semicolon at the end. 

Syntax for defining a class is  class class name {  Access specifier:  Data members  Member functions  };  Example of a class  class student  { private:   int rollno;  char name[20];    public: void read()  {  cout<<”Enter the roll no. and name”;  cin>>rollno>>name;  }  void display()  {  cout<<”The roll no. and name are:”<<endl;  cout<<rollno<<name;  }  Here, private and public are the access specifiers, rollno and name are the data members and  read() and display() are the member functions of the class student .  

Data member and member function of a class   The variables declared inside a class is called the data members of the class and the functions  declared inside a class are the member functions of the class. For the class class student  {  private:   int rollno;  char name[20];  public:  void read()  {  cout<<”Enter the roll no. and name”;  cin>>rollno>>name; }  void display()  {  cout<<”The roll no. and name are:”<<endl;  cout<<rollno<<name;  }  };  rollno and name[20] are the data members and read() and display() are the member functions. The variables declared inside a class is called the data members of the class and

Object   An Object is an instance of a Class. When a class is defined, no memory is allocated but when it  is instantiated (i.e. an object is created) memory is allocated.  Syntax for declaring Objects of a class  ClassName objectName;  class student  {  ……  ……..  };  The declaration of an object of the class student is as follows-   student S;  Accessing data members and member functions :     The data members and member functions of class can be accessed using the dot(‘.’) operator  with the object. For example if the name of object is obj to access the member function with the  name printName() then we will have to write obj.printName() .  The public data members are also accessed in the same way as the member functions given  however the private data members are not allowed to be accessed directly by the object.  

Access specifier of member accessing modes   There are three access specifiers - private, public and protected . private:- In this mode, the members are accessible to only the member functions within the  class. Any function outside the class cannot access the private members. In this mode, the  members are not inheritable.  public :- In this mode, the members are accessible to any functions outside or inside the class.  The members are inheritable in this mode.  protected:- It is similar to the private mode, but the exception here is that the members are  inheritable in this mode . 

C   C++ 1 C supports procedural programming  paradigm for code development. C++ supports both procedural and object  oriented programming paradigms; therefore  C++ is also called a hybrid language. 2  C does not support object oriented  programming; therefore it has no support  for polymorphism, encapsulation, and  inheritance. Being an object oriented programming  language C++ supports polymorphism,  encapsulation, and inheritance. 3  In C (because it is a procedural  programming language), data and  functions are separate and free entities. In C++ (when it is used as object oriented  programming language), data and functions  are encapsulated together in form of an object.  For creating objects class provides a blueprint  of structure of the object. 4  In C, data are free entities and can be  manipulated by outside code. This is  because C does not support information  hiding. In C++, Encapsulation hides the data to  ensure that data structures and operators are  used as intended. 5  C, being a procedural programming, it is a  function driven language. While, C++, being an object oriented  programming, it is an object driven language. 6  C does not support function and operator  overloading. C++ supports both function and operator  overloading. 7  C does not allow functions to be defined  inside structures. In C++, functions can be used inside a  structure.

8  C uses functions for input/output. For  example scanf and printf . C++ uses objects for input output. For  example cin and cout. 9  C does not support reference variables.  C++ supports reference variables. 10  C has no support for virtual and friend  functions. C++ supports virtual and friend functions. 11  C provides malloc() and calloc() functions  for dynamic memory allocation,  and free() for memory de-allocation. C++ provides new operator for memory  allocation and delete operator for memory de allocation. 12  C does not provide direct support for error  handling (also called exception handling) C++ provides support for exception handling.  Exceptions are used for "hard" errors that  make the code incorrect.

UNIT 4 POINTERS AND REFERENCES

Consider the following code: Pointers References int i; int i; int *pi = &i; int &ri=I; In both cases the situation is as follows: Both pi and ri contain addresses that point to the location of i, but the difference lies in the appearance between references and pointers when they are used in expressions. In order to assign a value of 4 to i in both cases, we write: *pi = 4; ri = 4; Note the, when using pointers, the address must be dereferenced using the *, whereas, when using references, the address is dereferenced without using any operators at all! The main effect of this is that the address can directly be manipulated if it is a pointer. We can do things such as: pi++; pi i addr addr addr r i

to increment to the next address. This is not possible using references. Therefore, to summarize, a pointer can point to many different objects during its lifetime, a reference can refer to only one object during its lifetime. When to Use Pointers vs References References are the preferred way of indirectly accessing a variable. They are also a little safer than pointers and, in some cases, are the only way to achieve a particular result such as overloading certain operators. Consider the following: enum day { Sunday, Monday, ... }; If we define a variable; day x; and we wanted to write a method to overload the ++ operator such that the statement ++x; increments x to the next day, we could write the following: day &operator++(day &d) { d = (day)(d + 1); return d; } Using pointers, we may think that the following declaration would work: day *operator++(day *d); However, this statement will not even compile because every overloaded operator function must either be a member of a class, or have a parameter of type T, T &, or T const &, where T is a class or enumeration type. So in this particular case, using a reference is the only way to do it

UNIT 5 EXCEPTION AND FILE HANDLING

C++ EXCEPTION HANDLING 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 identifyes 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 look try { // protected code }catch( ExceptionName e1 ) { // catch block }catch( ExceptionName e2 ) { // catch block }catch( ExceptionName eN ) { // catch block }

Throwing Exceptions 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. Exceptions can be thrown anywhere within a code block using throw statements. The operand of the throw statements determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown. Following is an example of throwing an exception when dividing by zero condition occurs: double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); } Catching Exceptions The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch

try { // protected code }catch( ExceptionName e ) { // code to handle ExceptionName exception } Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the parentheses enclosing the exception declaration as follows : try { // protected code }catch(...) { // code to handle any exception }

The following is an example, which throws a division by zero exception and we catch it in catch block. #include <iostream> using namespace std; double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); } int main () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; }catch (const char* msg){ cerr << msg << endl; } return 0; }

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++ 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: s td:exception std:bad_cast std:bad_exception std:logic_failure std:bad_tyepid std:bad_alloc std:runtime_error s td:domain_error s td:length_error s td : invalid _ argument s td:range_error s td:out_of_range s td:underflow_error s td:overflow_error

Here is the small description of each exception mentioned in the above hierarchy: Exception Description std::exception An exception and parent class of all the standard C++ exceptions. std::bad_alloc This can be thrown by new. std::bad_cast This can be thrown by dynamic_cast. std::bad_exception This is useful device to handle unexpected exceptions in a C++ program std::bad_typeid This can be thrown by typeid. std::logic_error An exception that theoretically can be detected by reading the code. std::domain_error This is an exception thrown when a mathematically invalid domain is used. std::invalid_argument This is thrown due to invalid arguments. std::length_error This is thrown when a too big std::string is created. std::out_of_range This can be thrown by the at method from for example a std::vector and std::bitset<>::operator[]. std::runtime_error An exception that theoretically can not be detected by reading the code. std::overflow_error This is thrown if a mathematical overflow occurs. std::range_error This is occured when you try to store a value which is out of range. std::underflow_error This is thrown if a mathematical underflow occurs .

#include <iostream> #include <exception> 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; } 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:

catch(std::exception& e) { //Other errors } } This would produce the following result: MyException caught C++ Exception Here, what is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause of an exception.

THANK YOU