Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

Introduction To Object Oriented Concepts

The document introduces object-oriented programming concepts such as objects, classes, encapsulation, abstraction, inheritance, polymorphism, and relationships between objects. It discusses how objects contain data fields and methods, and how classes are used to create object templates. It also covers object-oriented principles like encapsulation, inheritance, polymorphism, and relationships. Specific examples are provided like modeling employees and vehicles as classes.

Uploaded by

Curo Heal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Introduction To Object Oriented Concepts

The document introduces object-oriented programming concepts such as objects, classes, encapsulation, abstraction, inheritance, polymorphism, and relationships between objects. It discusses how objects contain data fields and methods, and how classes are used to create object templates. It also covers object-oriented principles like encapsulation, inheritance, polymorphism, and relationships. Specific examples are provided like modeling employees and vehicles as classes.

Uploaded by

Curo Heal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Introduction to Object oriented Concepts

• The core of the object-oriented programming


is to create an object, in code, that has certain
properties and methods.
• While designing we try to see whole world in
the form of objects.
• Example: Bank Account
Transition from procedural to object oriented
approach
• Procedural programming separates the data of
the program from the operations that
manipulate the data.

• Fundamental advantage of Object Oriented


programming is that the data and the
operations that manipulate the data are both
encapsulated in the object.
The Object-oriented approach

• Object-Oriented Approach programming is


used to manage the complexity of software
systems. OOP methods make code more
maintainable. Identifying the source of errors
becomes easier because objects are self-
contained.
Fundamentals of Object Oriented
Approach
• OOP envisions software as a collection of cooperating
objects rather than a collection of functions or simply
a list of commands. In OOP, each object can receive
messages, process data, and send messages to other
objects. Each object can be viewed as an independent
little machine with a distinct role or responsibility.
• In the object-oriented approach, the focus is on
capturing the structure and behavior of information
systems into small modules that combines both data
and process. The main aim of Object
Oriented approach, is to improve the quality and
productivity of system by making it more usable.
Encapsulation, Abstraction, Modularity
Polymorphism, and Inheritance
• Encapsulation is the packing of data and functions into
one component (class) and then controlling access to
that component.
• Abstraction, helps to increase security of an application
as only important details are provided to the user.
• Polymorphism is the presentation of one interface for
multiple data types.
• Inheritance, the data abstraction can be carried up
several levels, that is, classes can have super-classes
and sub-classes
• Modularity enables re-usability and minimizes
duplication.
Why Objects?

• An object has a state and behavior. The state


of an object is stored in fields (variables),
while methods (functions) display the object‘s
behavior.
• We create objects to modify them, move them
around, change their filed values, call their
methods, combine them with other objects
and communicate with other Objects
Inheritance
Example : Employee – Manager(s)
Inheritance
Example : Class Vehicle {}; //can  ply on road  (car, bus.)
Class Flying{}; // Can fly (helicopter, glider)
Class Fying_Vehicle:public Vehicle, public Flying {}; // (aeroplane).
Inheritance
Example : Person - Employee – Manager(s)
Inheritance
Example : Employee – Manager(s)
Early Binding vs Late Binding
• In early binding, the compiler matches the
function call with the correct function
definition at compile time. It is also known
as Static Binding or Compile-time Binding.

• In the case of late binding, the compiler


matches the function call with the correct
function definition at runtime. It is also
known as Dynamic Binding or Runtime
Binding.
Object relationships
• There are many different kinds of
relationships two objects may have in real-
life, and we use specific “relation type”
words to describe these relationships. For
example: a square “is-a” shape. A car “has-
a” steering wheel. A computer programmer
“uses-a” keyboard. A flower “depends-on” a
bee for pollination. A student is a “member-
of” a university. And our brain exists as
“part-of” us.
Object relationships
• Multiplicity answers the question ‘How many,
if any?’. While modelling an association, the
multiplicity is labelled on one or either end of
the line connecting the two classes, depending
on whether the association is unidirectional or
bidirectional. The role may also be mentioned.
The Science Museum would be said to have
many exhibits (composition) and many visitors
(aggregation).
Object relationships
• For aggregations and compositions, apply the ‘is part
of’ rule.
• For aggregations, the part should be a real world object
and should have attributes and methods of its own.
However if there is no necessity for tracking it in the
application, then there is no need to create a class out
of it and model it.
• Multiplicity should be shown when modelling
association, aggregation, and composition relationship.
• Multiplicity may change as business rules change
• Associations are inherited
Static Members
• A static member is shared by all objects of the class. All
static data is initialized to zero when the first object is
created, if no other initialization is present.
• A static member function can be called even if no
objects of the class exist and the static functions are
accessed using only the class name and the scope
resolution operator ::
• A static member function can only access static data
member, other static member functions and any other
functions from outside the class
• Static member functions have a class scope and they
do not have access to the this pointer of the class
Static Members
• static member functions do not have this
pointer.
• A static member function cannot be virtual
• A static member function can not be
declared const, volatile, or const volatile.
• Global functions and data may be accessed by
static member function.
Static Members
Overloading of static member functions
• class Loan{
• static double rate_of_interest;
• double loan_amount;
• double period;
• public:
• //... other functions
• static void setRateOfInerest(double new_rate){
• rate_of_interest = new_rate;
• }
• static void setRateOfInerest(double val, int inc_dec){
• if(inc_dec)
• rate_of_interest += val;
• else
• rate_of_interest -= val;
• }

• };

• int main(){
• return 0;
• }
Objects on the heap
• C++ programming language allows both auto(or
stack allocated) and dynamically allocated (heap
allocated) objects.
• C++ supports stack allocated objects for the reason
of runtime efficiency. Stack based objects are
implicitly managed by C++ compiler. They are
destroyed when they go out of scope and
dynamically allocated objects must be manually
released, using delete operator otherwise memory
leak occurs.
Objects on the heap
• #include <iostream>
• using namespace std;

• class Test
• {
• // Notice this, new operator function is private
• void* operator new(size_t size);
• int x;
• public:
• Test() { x = 9; cout << "Constructor is called\n"; }
• void display() { cout << "x = " << x << "\n"; }
• ~Test() { cout << "Destructor is executed\n"; }
• };

• int main()
• {
• // following line cause a compile time error.
• Test* obj=new Test(); //Error line

• Test t; // Ok, object is allocated at compile time


• t.display();
• return 0;
• }
Use of this pointer
• this pointer is used as a pointer to the class
object instance by it’s members.
• this is a pointer pointing to current working
object.
• The this keyword is used to represent an
object that invokes the member function. It
points to the object for which this function
was called.
Use of this pointer
• #include <iostream>
• using namespace std;

• class Test
• {
• int x;
• public:
• Test (int x){ this->x = x; }
• Test() { x = 9; cout << "Constructor is called\n"; }
• void display() { cout << "x = " << x << "\n"; }
• ~Test() { cout << "Destructor is executed\n"; }
• };
• int main()
• {
• Test t1; t1.display();
• Test t2(100); t2.display();
• return 0;
• }
Overloading of Constant members
• void fun(const int i) { cout << "fun(const int)
called "; } void fun(int i) { cout << "fun(int )
called " ; } int main() { const int i = 10; fun(i);
return 0; }
Mutable Data member
• Mutable data member is that member which
can always be changed; even if the object
is const type.
• To make data member as a mutable, we need
to use mutable keyword.
Mutable Data member
• #include<iostream> • int main()
• using namespace std;
• {
• class Sample • const Sample s(10,20); // A const object
• {
• int x; mutable int y;
• cout<<endl <<"Value before change: ";
• public:
• Sample(int a=0, int b=0) { x=a; y=b;} • s.display();
• //function to set value of x
• void setx(int a=0) {x = a;} • s.setx(100);
• //function to set value of y
• //Error: x can not be changed, because
• //value of y being changed, even if member function is object is constant.
constant. • s.sety(200);
• void sety(int b=0) const {y = b;}
• //y still can be changed, because y is
• //function to display x and y.
mutable.
• //this has to be const type, if member function is
constant type. • cout<<endl<<"Value after change: ";
• void display() const
• {
• s.display();
• cout<<endl<<"x: "<<x<<" y: "<<y<<endl; •
• } • return 0;
• };
• }
Constant objects
• const class objects can only explicitly
call const member functions
• # include <iostream> • int main()
• using namespace std; • {
• const Something something; //
• class Something
calls default constructor
• {


public:
• int m_value; • //something.m_value = 5; //
• compiler error: violates const
• Something(): m_value(0) { } • //something.setValue(5); //
• compiler error: violates const
• void setValue(int value) { m_value = value; } • cout << something.getValue();
• //int getValue() { return m_value ; }
• return 0;
• int getValue() const { return m_value ; }
• }; • }
Memory Management
• Code Segment: Compiled program with executive instructions are
kept in code segment. It is read only.
• Data Segment: Global variables and static variables are kept in data
segment. It can read / write.
• Stack: A stack is usually pre-allocated memory. The stack is a LIFO
data structure. Each new variable is pushed onto the stack. Once
variable goes out of scope, memory is freed. Once a stack variable is
freed, that region of memory becomes available for other variables.
The stack grows and shrinks as functions push and pop local
variables. It stores local data, return addresses, arguments passed
to functions and current status of memory.
• Heap: Memory is allocated during program execution. Memory is
allocated using dynamic memory allocation and it can be de-
allocated.
New vs malloc
• Memory allocated from 'Free Store' • Memory allocated from 'Heap'
• Returns a fully typed pointer. • Returns a void*
• new (standard version) never returns a
NULL (will throw on failure)
• Returns NULL on failure
• Are called with Type-ID (compiler • Must specify the size required in
calculates the size) bytes.
• Has a version explicitly to handle arrays. • Allocating array requires manual
• Reallocating (to get more space) not calculation of space.
handled intuitively (because of copy
• Reallocating larger chunk of
constructor).
• Whether they call malloc/free is memory simple (No copy
implementation defined. constructor to worry about)
• Can add a new memory allocator to deal • They will NOT call new/delete
with low memory (set_new_handler) • No way to splice user code into
• operator new/delete can be overridden the allocation sequence to help
legally
with low memory.
• constructor/destructor used to
initialize/destroy the object • malloc/free can NOT be
overridden legally
Notes
New vs malloc vs calloc
• malloc allocates uninitialized memory. The allocated
memory has to be released with free. It takes argument as
size of memory to allocate.
• Ex: (typecast datatype pointer) malloc(No_Elements * sizeof(datatype))
• calloc is like malloc but initializes the allocated memory with
0. It needs to be freed with free.
• Ex: (typecast datatype pointer) calloc(No_Elements, sizeof(datatype))
• new initializes the allocated memory by calling the
constructor (if it's an object). Memory allocated
with new should be released with delete (which in turn calls
the destructor). It does not need you to manually specify
the size you need and cast it to the appropriate type.
• Ex: new [Objectconstructor]
Deep copy v/s Shallow copy
• In a deep copy, the fields that • In a shallow copy, a new
are stored by value are copied instance of the type is created
as before, but the pointers to and the values are copied into
objects stored by reference the new instance. The
are not copied. Instead, a reference pointers are also
deep copy is made of the copied just like the values.
referenced object, and a Therefore, the references are
pointer to the new object is pointing to the original objects.
stored. Any changes that are Any changes to the members
made to those referenced that are stored by reference
appear in both the original and
objects will not affect other
the copy, since no copy was
copies of the object
made of the referenced object.
Constructor Overloading
• Constructor can be • class Base{
• public:
overloaded with in a class
• Base(){
similar way as function • cout << "Base Default Constructor";
overloading. • }
• Overloaded constructors • Base(string s){
have the same name (name • cout << "Base Constructor with String
value ";
of the class) but different
• }
number of arguments. • Base(int i){
• Depending upon the • cout << "Base Constructor with integer
number and type of value " << i << endl;
arguments passed, specific • }
• };
constructor is called.
Explicit constructor
• class A { • class A {
• public:
• public: • explicit A();
• A(); • explicit A(int);

• A(int); explicit A(string, int = 0); };
• Only following statements are
• A(string, int = 0); legal:
• }; • A a1;
• A a2 = A(1);
• The following • A a3(1);
declarations are legal. • A a4 = A("Venditti");
• A c = 1; • A* p = new A(1);
• A a5 = (A)1;
• A d = (string)"Venditti"; • A a6 = static_cast<A>(1);
Copy constructor & Generic Copy constructor
Copy Constructor v/s Assignment operator

• The copy constructor is an • The assignment operator


overloaded constructor. is a bitwise operator.
• Using copy constructor • An assignment operator
you can initialize a new copies one object to the
object with an already other object, both of
existing object. which are already exists.
• If you do not define any • If you do not overload
copy constructor in the the "=" operator, then a
program, C++ compiler bitwise copy will be
implicitly provides one. made.
Copy Constructor v/s Assignment operator
• A copy constructor is initialized • an assignment operator is
whenever a new object is initialized invoked only when an object is
with an already existing object, being assigned to another object.
when an object is passed to a • When an object is being
function as a non reference
initialized using an assignment
parameter, or when an object is
operator then the initialized and
returned from a function.
initializing objects shares the
• When an object is being initialized
same memory location
using copy constructor, the
initializing object and the initialized • If you do not overload an
object shares the different memory assignment operator then a
location bitwise copy operation is
• If you do not explicitly define a copy performed
constructor then the compiler
provides one.
Copy Constructor v/s Assignment operator
• class Democopy{
• int num;
• public:
• Democopy(){ } //default constructor
• Democopy(int a){ num=a; } //overloading
constructor
• Democopy(Democopy &c ){ num = c.num; }//Copy
constructor
• void show( ){ cout<< num; }
• };
• int main(){
• Democopy A(200); //Object A created and
initialized
• Democopy B(A); // Copy constructor called
• Democopy C=A; // Copy constructor called
• Democopy D;
• D=A; //copy constructor not called because
• // object D not newly created object.
• //it is an assignment operation.
• return 0;
• }
Initializer List
• Initializer list is used to initialize data
members. The syntax begins with a colon(:)
and then each variable along with its value
separated by a comma. The initializer list does
not end in a semicolon.
• class Base {
• private: int value;
• public:
• // default constructor
• Base(int value):value(value) { cout << "Value is " << value; }
• };
Initializer List
• When reference type.
• class Base {
• private: int &ref;
• public:
• Base(int &ref):ref(ref) { cout << "Value is " << ref; }
• };
• When const data member
• class Base {
• private: const int cvar;
• public:
• Base(int c_var):cvar(cvar) { cout << "Value is " << cvar; }
• };
Initializer List
• When Using Objects
• class Example{
public : Example(){ cout << “Example Constructor”;}
Example(int x){ cout << “Example int Constructor”;}
• };
• class Test{
int data;
Example eobj;
public:
//Test(){ data = 10; eobj = Example(10); } //assignment
Test(): data(10), eobj(Example(10)){ } //initialization
// or // Test(): data(10), eobj(10){ } //initialization
};
int main(){
Test test_obj;
return 0;
}
list Initialization order
• Order of member initializers in the list is irrelevant
• If the constructor is for the most-derived class,
virtual base classes are initialized in the order in
which they appear in depth-first left-to-right traversal
of the base class declarations (left-to-right refers to
the appearance in base-specifier lists)
• Then, direct base classes are initialized in left-to-right
order as they appear in this class's base-specifier list
• Then, non-static data members are initialized in
order of declaration in the class definition
• Finally, the body of the constructor is executed
Initialization v/s Assignment
• Assignment is storing a value in the location
using assignment operator
• A value is assigned to the variable at the time
of declaration itself, it is called initialization.
• If a variable is declared without initialization,
it will have random garbage value stored in it.
ObjeDestructor - Delete vs Freect Cleanup

• De-allocating memory
• delete free the allocated memory and calls destructor.
But free() de-allocate memory but does not call
destructor. delete is faster than free() because an
operator is always faster than a function.
• Explicit call to destructor is only necessary when object
is placed at particular location in memory by using
placement new. Destructor should not be called
explicitly when the object is dynamically allocated
because delete operator automatically calls destructor

• int main()
class Base{
• public: • {
• Base(){ • Test(); // Explicit call to
• cout << "Bsae Constructor";
constructor
• }
• ~Base(){ • cout << endl;
• cout << "Bsae Distructor"; • Test t; // local object
• }
• cout << endl;
• };
• class Test : Base • t.~Test(); // Explicit call to
• { destructor
• public: • cout << endl;
• Test() { cout << "Constructor is
executed\n"; } • t.simple();
• ~Test() { cout << "Destructor is • cout << endl;
executed\n"; }
• void simple(){ • return 0;
• cout << "Simple method"; • }
• }
• }; Notes
• We know that the destructor is a routine that has
the same name as the class with a ~ symbol
preceding it and is called automatically by the
compiler during the destruction of an object. A
compiler synthesized destructor for class would do
a member wise destruction of the member objects
of class objects and their base class sub-objects. i.e.
if user-defined destructors are available for any
member objects or base class sub-objects, the
compiler would invoke the corresponding methods.
Preventing destroying object instance

• As long as you store a copy of the pointer


elsewhere, you can access the memory out of
scope.
dangling pointers
• Dangling pointers in computer programming are
pointers that pointing to a memory location that has
been deleted (or freed).
• Dangling pointers arise during object destruction,
when an object that has an incoming reference is
deleted or deallocated, without modifying the value
of the pointer, so that the pointer still points to the
memory location of the deallocated memory.
• The system may reallocate the previously freed
memory, unpredictable behavior may result as the
memory may now contain completely different data.
dangling pointers
• #include <iostream> • #include <iostream>
• #include<string.h> • #include<string.h>
• using namespace std; • #include <stdlib.h>>
• char *getHello()
• using namespace std;
• {

• int main()
char str[10];
• strcpy(str,"Hello!"); •{
• return(str); • char **strPtr;
• } • char *str = "Hello!";
• int main() •
• {
• strPtr = &str;
• //str falls out of scope
• //function call char *getHello() is now a • free(str);
dangling pointer • // strPtr is now a dangling pointer
• cout << getHello(); • cout << *strPtr;
• } • return 0;
•}
dangling pointers can handle by assigning NULL; after free
str=NULL;
• class Base{
• int main()
• int data;
• public: • {
• Base(): data(10){ • Base *p = new Base[4];
• cout << "Bsae Constructor\n";
• for(int i=0;i<4;i++)
• }
• ~Base(){ • (p+1)->sample(i);
• cout << "Bsae Distructor\n"; •
• } • delete p;
• void sample(int val){
• cout << "Simple value " << val << " • p = NULL;
and DATA " << data << endl; • for(int i=0;i<4;i++)
• }
• (p+1)->sample(i);
• };
• }
• C++ allows both auto(or stack allocated) and
dynamically allocated objects.
• Stack allocated objects for the reason of
runtime efficiency. Stack based objects are
implicitly managed by C++ compiler. They are
destroyed when they go out of scope. 
• Dynamically allocated objects must be
manually released, using delete operator.
Destroying array of objects
• Delete [] ptr;
• Ptr = NULL;
Smart pointer concept
• A Smart pointer is a composition class that is
designed to manage dynamically allocated memory
and ensure that memory gets deleted when
the smart pointer object goes out of scope.
• a smart pointer is an abstract data type that
simulates a pointer while providing added features,
such as automatic memory management or bounds
checking. Such features are intended to reduce bugs
caused by the misuse of pointers, while retaining
efficiency.
Smart pointer concept
• #include <iostream>
• template<class T>
• class Auto_ptr1 • Int main(){
• { • Auto_ptr1<Resource> ptr(new
• T* m_ptr;
Resource); // ptr now owns the Resource
• public:
• // Pass in a pointer to "own" via the constructor •     int x;
• Auto_ptr1(T* ptr=nullptr) :m_ptr(ptr) {} •     std::cout << "Enter an integer: ";
• // The destructor will make sure it gets deallocated •     std::cin >> x;
• ~Auto_ptr1() { delete m_ptr; }
• // Overload dereference and operator-> so we can
•     if (x == 0)
use Auto_ptr1 like m_ptr. •         return; // the function returns early
• T& operator*() const { return *m_ptr; } •     // do stuff with ptr here
• T* operator->() const { return m_ptr; }
• }; // A sample class to prove the above works
•     ptr->sayHi();
• class Resource { • Auto_ptr1<Resource> res(ptr); //
• public: Alternatively, don't initialize res and then
•   Resource() { std::cout << "Resource acquired\n"; } assign res = ptr;
•  ~Resource() { std::cout << "Resource
destroyed\n"; }
• return 0;
•     void sayHi() { std::cout << "Hi\n"; } • }
• };
Exception handling
• Exceptions provide a way to react to exceptional
circumstances (like runtime errors) in programs by
transferring control to special functions
called handlers.
• To catch exceptions, a portion of code is placed under
exception inspection. This is done by enclosing that
portion of code in a try-block. When an exceptional
circumstance arises within that block, an exception is
thrown that transfers the control to the exception
handler. If no exception is thrown, the code continues
normally and all handlers are ignored.
Exceptions
• try { • try {
• // code here • try {
• • // code here
}
• }
• catch (int param) {
• catch (int n) {
• cout << "int exception"; } • throw;
• catch (char param) { • }
• cout << "char exception"; } • }
• catch (...) { • catch (...) {
• cout << "default • cout << "Exception occurred";
exception"; } • }
Standard & user exceptions
• The C++ Standard library provides a base class
specifically designed to declare objects to be thrown as
exceptions. It is called std::exception and is defined in
the <exception> header.
• This class has a virtual member function called what that
returns a null-terminated character sequence (of
type char *) and that can be overwritten in derived
classes to contain some sort of description of the
exception.
• All exceptions thrown by components of the C++
Standard library throw exceptions derived from
this exception class
• #include <iostream>
• #include <exception>
• using namespace std;

• class myexception: public exception


• {
• virtual const char* what() const throw()
• {
• return "My exception happened";
• }
• } myex;

• int main () {
• try
• {
• throw myex;
• }
• catch (exception& e)
• {
• cout << e.what() << '\n';
• }
• return 0;
• }
exception description
bad_alloc thrown by new on allocation failure
thrown by dynamic_cast when it fails
bad_cast
in a dynamic cast
thrown by certain dynamic exception
bad_exception
specifiers
bad_typeid thrown by typeid
bad_function_call thrown by empty function objects
thrown by shared_ptr when passed
bad_weak_ptr
a bad weak_ptr
Header <exception> defines two generic exception types that can
be inherited by custom exceptions to report errors
exception description
error related to the internal logic of
logic_error
the program

runtime_error error detected during runtime


• try
• {
• int* myarray= new int[1000];
• }
• catch (exception& e)
• {
• cout << "Standard exception: " << e.what() << endl;
• }
• The exception that may be caught by the exception
handler in this example is a bad_alloc.
Set terminate handler function
• A terminate handler function is • #include <iostream> // std::cerr
a function automatically called • #include <exception> //
std::set_terminate
when the exception handling
• #include <cstdlib> // std::abort
process has to be abandoned
for some reason. This happens
• void myterminate () {
when no catch handler can be • std::cerr << "terminate handler
found for a thrown exception, called\n";
or for some other exceptional • abort(); // forces abnormal
circumstance that makes termination
impossible to continue the • }
exception handling process. • int main (void) {
• Function that takes no • std::set_terminate (myterminate);
• throw 0; // unhandled exception:
parameters and returns no
calls terminate handler
value (void).
• return 0;
• }
Set unexpected handler function
• • Function that takes no parameters and
The unexpected handler function is a
returns no value (void).
function automatically called when a • #include <iostream> // std::cerr
function throws an exception that is not • #include <exception> // std::set_unexpected
in its dynamic-exception- • void myunexpected () {
specification (i.e., in its throw specifier) • std::cerr << "unexpected called\n";
• The unexpected handler function can • throw 0; // throws int (in exception-
handle the exception and shall end specification)
• }
either by teminating (calling terminate
• void myfunction () throw (int) {
or some other method, such as exit or • throw 'x'; // throws char (not in exception-
abort) or by throwing an exception specification)
(even rethrowing the same exception • }
again). If the exception thrown (or • int main (void) {
rethrown) is not in the function's • std::set_unexpected (myunexpected);
dynamic-exception-specification but • try {
bad_exception is, a bad_exception is • myfunction();
• }
thrown. Otherwise, if the new
• catch (int) { std::cerr << "caught int\n"; }
exception is not in the dynamic- • catch (...) { std::cerr << "caught some other
exception-specification either, exception type\n"; }
terminate is automatically called. • return 0;
• }
Custom Exceptions
• double divide ( double a, double b)
{
if ( b == 0 ) // !! Division by zero
throw "Division by zero";
else
return a / b;
}

try
{
double res = divide ( 1, 0);
}
catch ( char* c)
{
cout << c;
}
Custom Exceptions
• int main()
• class MyException : {
public std::exception try
{
{ throw MyException();
}
const char * what () catch (MyException& e)
const throw () {
std::cout << "MyException caught" <<
{ std::endl;
return "C++ Exception"; std::cout << e.what() << std::endl;
}
} catch (std::exception& e)
{
} // Other errors
}
}
Custom Exceptions
• class MyException : public std::exception {
const char* file;
int line; • int main()
const char* func; {
const char* info; try
{
public:
MyException(const char* msg, const
some_function()
char* file_, int line_, const char* func_, }
const char* info_ = "") : catch (MyException& ex)
std::exception(msg), {
file (file_), std::cout << ex.what() << ex.get_info()
line (line_), << std::endl;
func (func_), std::cout << "Function: " <<
info (info_){ }
ex.get_func() << std::endl;
const char* get_file() const { return file; }
int get_line() const { return line; } return EXIT_FAILURE;
const char* get_func() const { return func; }
}
const char* get_info() const { return }
info; }

You might also like