SlideShare a Scribd company logo
typeid
• It is used to obtain an object's type. You must include the header <typeinfo>
in order to use typeid.
• Its typeid returns a reference to an object of type type_info that describes the
type of object.
• The type_info class defines the following public members:
bool operator = = (const type_info &ob);
bool operator !=(const type_info &ob);
bool before(const type_info &ob);
const char *name();
• The overloaded = = and != provide for the comparison of types.
• The before() function returns true if the invoking object is before the object
used as a parameter in collation order. (This function is mostly for internal
use only. Its return value has nothing to do with inheritance or class
hierarchies) .
• The name() function returns a pointer to the name of the type
Example: Using typeid
#include <iostream>
#include <typeinfo>
using namespace std;
class myclass1 {};
class myclass2 {};
int main()
{
int i, j;
float f;
char *p;
myclass1 ob1;
myclass2 ob2;
cout << "The type of i is: " << typeid(i).name() << endl;
cout << "The typeof f is: " << typeid(f).name() << endl;
cout << "The type of p is: " << typeid(p).name() << endl;
cout << "The type of ob1 is: " << typeid(ob1).name() << endl;
cout << "The type of ob2 is: " << typeid(ob2).name() << "n";
if(typeid(i) == typeid(j))
cout << "The types of i and j are the samen";
if(typeid(i) != typeid(f))
cout << "The types of i and f are not the samen";
if(typeid(ob1) != typeid(ob2))
cout << "ob1 and ob2 are of differing typesn";
return 0;
}
Output:
The type of i is: i
The typeof f is: f
The type of p is: Pc
The type of ob1 is: 8myclass1
The type of ob2 is: 8myclass2
The types of i and j are the same
The types of i and f are not the same
ob1 and ob2 are of differing types
Using typeid, one can determine at run time the type of the object that is being pointed
to by a base-class pointer. The following program demonstrates this principle.
#include <iostream>
#include <typeinfo>
using namespace std;
class Mammal
{
public:
virtual bool lays_eggs()
{ return false; }
};
class Cat: public Mammal
{
public:
};
class Platypus: public Mammal
{
public:
bool lays_eggs()
{ return true; }
};
Cont.
int main()
{
Mammal *p, mammal;
Cat cat;
Platypus platypus;
p = &mammal;
cout << "p is pointing to an object of type ";
cout << typeid(*p).name() << endl;
p = &cat;
cout << "p is pointing to an object of type ";
cout << typeid(*p).name() << endl;
p = &platypus;
cout << "p is pointing to an object of type ";
cout << typeid(*p).name() << endl;
return 0;
}
Output:
p is pointing to an object of type 6Mammal
p is pointing to an object of type 3Cat
p is pointing to an object of type 8Platypus
Use a reference with typeid
#include <iostream>
#include <typeinfo>
using namespace std;
class Mammal
{
public:
virtual bool lays_eggs() { return false; } // Mammal is polymorphic
};
class Cat: public Mammal
{
public:
};
class Platypus: public Mammal
{
public:
bool lays_eggs() { return true; }
};
Cont.
// Demonstrate typeid with a reference parameter.
void WhatMammal(Mammal &ob)
{
cout << "ob is referencing an object of type ";
cout << typeid(ob).name() << endl;
}
int main()
{
Mammal AnyMammal;
Cat cat;
Platypus platypus;
WhatMammal(AnyMammal);
WhatMammal(cat);
WhatMammal(platypus);
return 0;
}
Output:
b is referencing an object of type 6Mammal
ob is referencing an object of type 3Cat
ob is referencing an object of type 8Platypus
Example: Demonstrating run-time type id.
#include <iostream>
using namespace std;
class Mammal
{
public:
virtual bool lays_eggs() // Mammal is polymorphic
{
return false;
}
};
class Cat: public Mammal
{
public:
};
class Platypus: public Mammal
{
public:
bool lays_eggs()
{
return true;
}
};
Cont.
class Dog: public Mammal
{
public:
};
// A factory for objects derived from Mammal.
Mammal *factory()
{
switch(rand() % 3 )
{
case 0:
return (new Dog);
case 1:
return (new Cat);
case 2:
return (new Platypus);
}
return 0;
}
Cont.
int main()
{
Mammal *ptr; // pointer to base class
int c=0, d=0, p=0;
// Generate and count objects
for(int i=0; i<10; i++)
{
ptr = factory(); // Generate an object
cout << "Object is " <<
typeid(*ptr).name();
cout << endl;
// count it
if(typeid(*ptr) == typeid(Dog)) d++;
if(typeid(*ptr) == typeid(Cat)) c++;
if(typeid(*ptr) == typeid(Platypus)) p+
+;
}
cout << endl;
cout << "Animals generated:n";
cout << " Dogs: " << d << endl;
cout << " Cats: " << c << endl;
cout << " Platypuses: " << p << endl;
return 0;
Output:
Object is 3Cat
Object is 3Cat
Object is 3Dog
Object is 3Cat
Object is 8Platypus
Object is 3Cat
Object is 3Cat
Object is 3Dog
Object is 3Dog
Object is 3Cat
Animals generated:
Dogs: 3
Cats: 6
Platypuses: 1
typeid and Template Classes
#include <iostream>
using namespace std;
template <class T>
class myclass
{
private:
T a;
public:
myclass(T i)
{
a = i;
}
};
Cont.
int main()
{
myclass<int> o1(10), o2(9);
myclass<double> o3(7.2);
cout << "nType of o1 is ";
cout << typeid(o1).name() << endl;
cout << "nType of o2 is ";
cout << typeid(o2).name() << endl;
cout << "nType of o3 is ";
cout << typeid(o3).name() << endl;
if(typeid(o1) == typeid(o2))
cout << "no1 and o2 are the same type
n";
if(typeid(o1) == typeid(o3))
cout << "nErrorn";
else
cout << "no1 and o3 are different types
n";
return 0;
}
Output:
Type of o1 is 7myclassIiE
Type of o2 is 7myclassIiE
Type of o3 is 7myclassIdE
o1 and o2 are the same type
o1 and o3 are different types
Example:
using namespace std;
#include <iostream>
#include <typeinfo>
class Shape
{
public:
virtual void enterData() = 0;
virtual void displayData() = 0;
};
class Rectangle : public Shape
{
int length, breadth;
public:
void enterData()
{
cout << "n Enter the length: ";
cin >> length;
cout << "n Enter the breadth: ";
cin >> breadth;
}
void displayData()
{
cout << "n Area = " << (length*breadth);
}
};
Cont.
int main()
{
Shape *p = nullptr;
Rectangle r ;
p = &r; // Upcasting
p->enterData();
p->displayData();
Rectangle *rec_ptr = nullptr;
rec_ptr = (Rectangle *)p; // Downcasting
rec_ptr->enterData();
rec_ptr->displayData();
return 0;
}
Cont.
• Note that down casting requires explicit casts, such as
(Rectangle *) p
• The code given above may compile and run without any problem.
• However, this is not a very good idea to cast a base class pointer to a derived type in
this manner.
• Derived classes are an extension of the base class and usually contain more
information than the base class. This can result in an unexpected loss of information
during casting.
• Therefore, we must ensure that no such loss of information occurs or necessary error
flag is raised if the casting cannot be done in a proper manner.
• This is where we need the mechanism of dynamic cast.
• We can use dynamic_cast for safe down casting of a base class pointer or a reference to
a subclass in an inheritance hierarchy.
• On successful casting, it returns a pointer of the converted type and, if we try to cast a
invalid type such as a object pointer which is not of the type of the desired subclass, it
fails but does it without creating a major problem.
• The syntax of dynamic_cast with pointer and reference respectively are:
<type> *ptr_derived = dynamic_cast<<type> *>(ptr_obj);
<type> ref_derived = dynamic_cast<<type> &> (ref_obj);
• Because it is not possible to return nullptr as an indication of an error when casting a
reference, dynamic_cast throws an exception as defined in the typeinfo header called
std::bad_cast.
• Therefore, it is a good programming practice to wrap dynamic cast operations within a
try/catch block.
Using dynamic_cast
Example: Using dynamic_cast
int main()
{
Shape *s = nullptr;
Rectangle r ;
s = &r;
s->enterData();
s->displayData();
Rectangle *r_ptr = nullptr;
// r_ptr = (Rectangle *)p;
try
{
r_ptr = dynamic_cast <Rectangle *> (s);
}
catch (std::bad_cast &bc)
{
cerr<<bc.what() << endl;
}
r_ptr->enterData();
r_ptr->displayData();
return 0;
}
namespace
• The namespace keyword allows you to partition the
global namespace by creating a declarative region.
• In essence, a namespace defines a scope.
• The general form of namespace is:
namespace name
{
// declarations
}
• Anything defined within a namespace statement is
within the scope of that namespace.
Example: namespace
#include <iostream>
using namespace std;
namespace first_space // first name space
{
void func()
{
cout << "Inside first_space" << endl;
}
}
namespace second_space // second name space
{
void func()
{
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main ()
{
func(); // This calls function from first name space.
return 0;
}
Output:
Inside first_space
Nested Namespaces
#include <iostream>
using namespace std;
namespace first_space // first name space
{
void func()
{
cout << "Inside first_space" << endl;
}
namespace second_space // second name space
{
void func()
{
cout << "Inside second_space" << endl;
}
}
}
using namespace first_space :: second_space;
int main ()
{
func(); // This calls function from second name space.
return 0;
}
Output:
Inside second_space
Example: Another way of accessing (without using keyword)
#include <iostream>
using namespace std;
namespace first_space
{
void func()
{ cout << "Inside first_space" << endl; }
}
namespace second_space
{
void func()
{ cout << "Inside second_space" << endl; }
}
int main ()
{
first_space :: func();
second_space :: func();
return 0;
}
Inside first_space
Inside second_space
Example: Identifying local and globar variables
#include <iostream>
using namespace std;
namespace first // Variable created inside namespace
{
int val = 500;
}
int val = 100; // Global variable
int main()
{
int val = 200; // Local variable
cout <<"first :: val = " << first :: val ;
cout << "nval = " << val;
cout << first :: val ;
return 0;
}
Output:
first :: val = 500
val = 200
Example: Defining a class inside a namespace
using namespace std;
#include <iostream>
#include <typeinfo>
using namespace std;
namespace ns
{
class Sample
{
public:
void display()
{
cout<<"Inside ns::Sample::display()"<< endl;
}
}; // End of the class
} // End of the namespace
int main()
{
ns::Sample s;
s.display();
return 0;
}
Example: Declaring a class inside a namespace and defining it outside the
namespace.
#include <iostream>
using namespace std;
namespace ns
{
class Sample; // Declaring class inside the namespace
}
class ns :: Sample // Defining class outside the namespace
{
public:
void display()
{
cout << “n Inside function display() ";
}
};
int main()
{
ns::Sample s ;
s.display();
return 0;
}
Example: Declaring two methods (one member function and other non-member
function) with same signatures inside a namespace
#include <iostream>
using namespace std;
namespace ns
{
void display();
class Sample
{
public:
void display();
};
}
// Defining methods of namespace
void ns :: Sample :: display()
{
cout << "n Inside display() function of Sample class";
}
void ns :: display()
{
cout << “n Inside non-member function display()";
}
int main()
{
ns::Sample s;
ns::display();
s.display();
return 0;
}
Nesting of namespaces (with two examples)
#include <iostream>
using namespace std;
namespace ns1
{
namespace ns2
{
namespace ns3
{
int var = 10;
}
using namespace ns3;
} // namespace ns2
using namespace ns2;
} // namespace ns1
int main()
{
cout << ns1 :: var;
return 0;
}
Output:
10
#include <iostream>
using namespace std;
namespace ns1
{
namespace ns2
{
namespace ns3
{
int var = 10;
}
}
}
using namespace ns1 :: ns2 :: ns3;
int main()
{
cout << var;
return 0;
}
Output:
10
Inline namespace
#include <iostream>
using namespace std;
namespace ns1
{
inline namespace ns2
{
inline namespace ns3
{
int var = 10;
}
}
}
int main()
{
cout << ns1::var << endl;
cout << ns1 :: ns2 :: var << endl;
cout << ns1 :: ns2 :: ns3 :: var << endl;
return 0;
}
Output:
10
10
10
Namespace Aliasing
#include <iostream>
namespace ns1
{
namespace ns2
{
namespace ns3
{
int var = 42;
}
}
}
namespace ns = ns1 :: ns2 :: ns3; // Aliasing
int main()
{
std::cout << ns :: var ;
}
Example: Illustrating the use of namespace
namespace CounterNameSpace
{
int upperbound, lowerbound;
class Counter
{
int count;
public:
Counter(int n)
{
if(n <= upperbound) count = n;
else count = upperbound;
}
void reset(int n)
{
if(n <= upperbound) count = n;
}
int run()
{
if(count > lowerbound) return count--;
else return lowerbound;
}
}; // End of the class
} // End of the namespace
Cont.
int main()
{
CounterNameSpace::upperbound = 100;
CounterNameSpace::lowerbound = 0;
CounterNameSpace::Counter ob1(10);
int i;
do
{
i = ob1.run();
cout << i << " ";
} while(i > CounterNameSpace::lowerbound);
CounterNameSpace::Counter ob2(20);
do
{
i = ob2.run();
cout << i << " ";
} while(i > CounterNameSpace::lowerbound);
cout << endl;
ob2.reset(100);
Notice that the declaration of a counter object
and the references to upperbound and
lowerbound are qualified by
CounterNameSpace. However, once an object
of type counter has been declared, it is not
necessary to further qualify it or any of its
members. Thus, ob1.run( ) can be called
directly; the namespace has already been
resolved.
CounterNameSpace::lowerbound = 90;
do
{
i = ob2.run();
cout << i << " ";
} while(i > CounterNameSpace::lowerbound);
return 0;
}
0 9 8 7 6 5 4 3 2 1 0 20 19 18 17 16 15 14 13 12
11 10 9 8 7 6 5 4 3 2 1 0 100 99 98 97 96 95 94
93 92 91 90
Ad

More Related Content

Similar to RTTI and Namespaces.pptx ppt of c++ programming language (20)

Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Data structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptxData structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
Nauman Rehman
 
Overloading
OverloadingOverloading
Overloading
poonamchopra7975
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
gertrudebellgrove
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
Andrey Akinshin
 
polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.
UdayGumre
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
Object Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptxObject Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptx
RashidFaridChishti
 
Unit 4
Unit 4Unit 4
Unit 4
siddr
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Data structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptxData structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
Nauman Rehman
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
gertrudebellgrove
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
Andrey Akinshin
 
polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.
UdayGumre
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
Object Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptxObject Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptx
RashidFaridChishti
 
Unit 4
Unit 4Unit 4
Unit 4
siddr
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 

Recently uploaded (20)

E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
Ad

RTTI and Namespaces.pptx ppt of c++ programming language

  • 1. typeid • It is used to obtain an object's type. You must include the header <typeinfo> in order to use typeid. • Its typeid returns a reference to an object of type type_info that describes the type of object. • The type_info class defines the following public members: bool operator = = (const type_info &ob); bool operator !=(const type_info &ob); bool before(const type_info &ob); const char *name(); • The overloaded = = and != provide for the comparison of types. • The before() function returns true if the invoking object is before the object used as a parameter in collation order. (This function is mostly for internal use only. Its return value has nothing to do with inheritance or class hierarchies) . • The name() function returns a pointer to the name of the type
  • 2. Example: Using typeid #include <iostream> #include <typeinfo> using namespace std; class myclass1 {}; class myclass2 {}; int main() { int i, j; float f; char *p; myclass1 ob1; myclass2 ob2; cout << "The type of i is: " << typeid(i).name() << endl; cout << "The typeof f is: " << typeid(f).name() << endl; cout << "The type of p is: " << typeid(p).name() << endl; cout << "The type of ob1 is: " << typeid(ob1).name() << endl; cout << "The type of ob2 is: " << typeid(ob2).name() << "n"; if(typeid(i) == typeid(j)) cout << "The types of i and j are the samen"; if(typeid(i) != typeid(f)) cout << "The types of i and f are not the samen"; if(typeid(ob1) != typeid(ob2)) cout << "ob1 and ob2 are of differing typesn"; return 0; } Output: The type of i is: i The typeof f is: f The type of p is: Pc The type of ob1 is: 8myclass1 The type of ob2 is: 8myclass2 The types of i and j are the same The types of i and f are not the same ob1 and ob2 are of differing types
  • 3. Using typeid, one can determine at run time the type of the object that is being pointed to by a base-class pointer. The following program demonstrates this principle. #include <iostream> #include <typeinfo> using namespace std; class Mammal { public: virtual bool lays_eggs() { return false; } }; class Cat: public Mammal { public: }; class Platypus: public Mammal { public: bool lays_eggs() { return true; } };
  • 4. Cont. int main() { Mammal *p, mammal; Cat cat; Platypus platypus; p = &mammal; cout << "p is pointing to an object of type "; cout << typeid(*p).name() << endl; p = &cat; cout << "p is pointing to an object of type "; cout << typeid(*p).name() << endl; p = &platypus; cout << "p is pointing to an object of type "; cout << typeid(*p).name() << endl; return 0; } Output: p is pointing to an object of type 6Mammal p is pointing to an object of type 3Cat p is pointing to an object of type 8Platypus
  • 5. Use a reference with typeid #include <iostream> #include <typeinfo> using namespace std; class Mammal { public: virtual bool lays_eggs() { return false; } // Mammal is polymorphic }; class Cat: public Mammal { public: }; class Platypus: public Mammal { public: bool lays_eggs() { return true; } };
  • 6. Cont. // Demonstrate typeid with a reference parameter. void WhatMammal(Mammal &ob) { cout << "ob is referencing an object of type "; cout << typeid(ob).name() << endl; } int main() { Mammal AnyMammal; Cat cat; Platypus platypus; WhatMammal(AnyMammal); WhatMammal(cat); WhatMammal(platypus); return 0; } Output: b is referencing an object of type 6Mammal ob is referencing an object of type 3Cat ob is referencing an object of type 8Platypus
  • 7. Example: Demonstrating run-time type id. #include <iostream> using namespace std; class Mammal { public: virtual bool lays_eggs() // Mammal is polymorphic { return false; } }; class Cat: public Mammal { public: }; class Platypus: public Mammal { public: bool lays_eggs() { return true; } };
  • 8. Cont. class Dog: public Mammal { public: }; // A factory for objects derived from Mammal. Mammal *factory() { switch(rand() % 3 ) { case 0: return (new Dog); case 1: return (new Cat); case 2: return (new Platypus); } return 0; }
  • 9. Cont. int main() { Mammal *ptr; // pointer to base class int c=0, d=0, p=0; // Generate and count objects for(int i=0; i<10; i++) { ptr = factory(); // Generate an object cout << "Object is " << typeid(*ptr).name(); cout << endl; // count it if(typeid(*ptr) == typeid(Dog)) d++; if(typeid(*ptr) == typeid(Cat)) c++; if(typeid(*ptr) == typeid(Platypus)) p+ +; } cout << endl; cout << "Animals generated:n"; cout << " Dogs: " << d << endl; cout << " Cats: " << c << endl; cout << " Platypuses: " << p << endl; return 0; Output: Object is 3Cat Object is 3Cat Object is 3Dog Object is 3Cat Object is 8Platypus Object is 3Cat Object is 3Cat Object is 3Dog Object is 3Dog Object is 3Cat Animals generated: Dogs: 3 Cats: 6 Platypuses: 1
  • 10. typeid and Template Classes #include <iostream> using namespace std; template <class T> class myclass { private: T a; public: myclass(T i) { a = i; } };
  • 11. Cont. int main() { myclass<int> o1(10), o2(9); myclass<double> o3(7.2); cout << "nType of o1 is "; cout << typeid(o1).name() << endl; cout << "nType of o2 is "; cout << typeid(o2).name() << endl; cout << "nType of o3 is "; cout << typeid(o3).name() << endl; if(typeid(o1) == typeid(o2)) cout << "no1 and o2 are the same type n"; if(typeid(o1) == typeid(o3)) cout << "nErrorn"; else cout << "no1 and o3 are different types n"; return 0; } Output: Type of o1 is 7myclassIiE Type of o2 is 7myclassIiE Type of o3 is 7myclassIdE o1 and o2 are the same type o1 and o3 are different types
  • 12. Example: using namespace std; #include <iostream> #include <typeinfo> class Shape { public: virtual void enterData() = 0; virtual void displayData() = 0; }; class Rectangle : public Shape { int length, breadth; public: void enterData() { cout << "n Enter the length: "; cin >> length; cout << "n Enter the breadth: "; cin >> breadth; } void displayData() { cout << "n Area = " << (length*breadth); } };
  • 13. Cont. int main() { Shape *p = nullptr; Rectangle r ; p = &r; // Upcasting p->enterData(); p->displayData(); Rectangle *rec_ptr = nullptr; rec_ptr = (Rectangle *)p; // Downcasting rec_ptr->enterData(); rec_ptr->displayData(); return 0; }
  • 14. Cont. • Note that down casting requires explicit casts, such as (Rectangle *) p • The code given above may compile and run without any problem. • However, this is not a very good idea to cast a base class pointer to a derived type in this manner. • Derived classes are an extension of the base class and usually contain more information than the base class. This can result in an unexpected loss of information during casting. • Therefore, we must ensure that no such loss of information occurs or necessary error flag is raised if the casting cannot be done in a proper manner. • This is where we need the mechanism of dynamic cast.
  • 15. • We can use dynamic_cast for safe down casting of a base class pointer or a reference to a subclass in an inheritance hierarchy. • On successful casting, it returns a pointer of the converted type and, if we try to cast a invalid type such as a object pointer which is not of the type of the desired subclass, it fails but does it without creating a major problem. • The syntax of dynamic_cast with pointer and reference respectively are: <type> *ptr_derived = dynamic_cast<<type> *>(ptr_obj); <type> ref_derived = dynamic_cast<<type> &> (ref_obj); • Because it is not possible to return nullptr as an indication of an error when casting a reference, dynamic_cast throws an exception as defined in the typeinfo header called std::bad_cast. • Therefore, it is a good programming practice to wrap dynamic cast operations within a try/catch block. Using dynamic_cast
  • 16. Example: Using dynamic_cast int main() { Shape *s = nullptr; Rectangle r ; s = &r; s->enterData(); s->displayData(); Rectangle *r_ptr = nullptr; // r_ptr = (Rectangle *)p; try { r_ptr = dynamic_cast <Rectangle *> (s); } catch (std::bad_cast &bc) { cerr<<bc.what() << endl; } r_ptr->enterData(); r_ptr->displayData(); return 0; }
  • 17. namespace • The namespace keyword allows you to partition the global namespace by creating a declarative region. • In essence, a namespace defines a scope. • The general form of namespace is: namespace name { // declarations } • Anything defined within a namespace statement is within the scope of that namespace.
  • 18. Example: namespace #include <iostream> using namespace std; namespace first_space // first name space { void func() { cout << "Inside first_space" << endl; } } namespace second_space // second name space { void func() { cout << "Inside second_space" << endl; } } using namespace first_space; int main () { func(); // This calls function from first name space. return 0; } Output: Inside first_space
  • 19. Nested Namespaces #include <iostream> using namespace std; namespace first_space // first name space { void func() { cout << "Inside first_space" << endl; } namespace second_space // second name space { void func() { cout << "Inside second_space" << endl; } } } using namespace first_space :: second_space; int main () { func(); // This calls function from second name space. return 0; } Output: Inside second_space
  • 20. Example: Another way of accessing (without using keyword) #include <iostream> using namespace std; namespace first_space { void func() { cout << "Inside first_space" << endl; } } namespace second_space { void func() { cout << "Inside second_space" << endl; } } int main () { first_space :: func(); second_space :: func(); return 0; } Inside first_space Inside second_space
  • 21. Example: Identifying local and globar variables #include <iostream> using namespace std; namespace first // Variable created inside namespace { int val = 500; } int val = 100; // Global variable int main() { int val = 200; // Local variable cout <<"first :: val = " << first :: val ; cout << "nval = " << val; cout << first :: val ; return 0; } Output: first :: val = 500 val = 200
  • 22. Example: Defining a class inside a namespace using namespace std; #include <iostream> #include <typeinfo> using namespace std; namespace ns { class Sample { public: void display() { cout<<"Inside ns::Sample::display()"<< endl; } }; // End of the class } // End of the namespace int main() { ns::Sample s; s.display(); return 0; }
  • 23. Example: Declaring a class inside a namespace and defining it outside the namespace. #include <iostream> using namespace std; namespace ns { class Sample; // Declaring class inside the namespace } class ns :: Sample // Defining class outside the namespace { public: void display() { cout << “n Inside function display() "; } }; int main() { ns::Sample s ; s.display(); return 0; }
  • 24. Example: Declaring two methods (one member function and other non-member function) with same signatures inside a namespace #include <iostream> using namespace std; namespace ns { void display(); class Sample { public: void display(); }; } // Defining methods of namespace void ns :: Sample :: display() { cout << "n Inside display() function of Sample class"; } void ns :: display() { cout << “n Inside non-member function display()"; } int main() { ns::Sample s; ns::display(); s.display(); return 0; }
  • 25. Nesting of namespaces (with two examples) #include <iostream> using namespace std; namespace ns1 { namespace ns2 { namespace ns3 { int var = 10; } using namespace ns3; } // namespace ns2 using namespace ns2; } // namespace ns1 int main() { cout << ns1 :: var; return 0; } Output: 10 #include <iostream> using namespace std; namespace ns1 { namespace ns2 { namespace ns3 { int var = 10; } } } using namespace ns1 :: ns2 :: ns3; int main() { cout << var; return 0; } Output: 10
  • 26. Inline namespace #include <iostream> using namespace std; namespace ns1 { inline namespace ns2 { inline namespace ns3 { int var = 10; } } } int main() { cout << ns1::var << endl; cout << ns1 :: ns2 :: var << endl; cout << ns1 :: ns2 :: ns3 :: var << endl; return 0; } Output: 10 10 10
  • 27. Namespace Aliasing #include <iostream> namespace ns1 { namespace ns2 { namespace ns3 { int var = 42; } } } namespace ns = ns1 :: ns2 :: ns3; // Aliasing int main() { std::cout << ns :: var ; }
  • 28. Example: Illustrating the use of namespace namespace CounterNameSpace { int upperbound, lowerbound; class Counter { int count; public: Counter(int n) { if(n <= upperbound) count = n; else count = upperbound; } void reset(int n) { if(n <= upperbound) count = n; } int run() { if(count > lowerbound) return count--; else return lowerbound; } }; // End of the class } // End of the namespace
  • 29. Cont. int main() { CounterNameSpace::upperbound = 100; CounterNameSpace::lowerbound = 0; CounterNameSpace::Counter ob1(10); int i; do { i = ob1.run(); cout << i << " "; } while(i > CounterNameSpace::lowerbound); CounterNameSpace::Counter ob2(20); do { i = ob2.run(); cout << i << " "; } while(i > CounterNameSpace::lowerbound); cout << endl; ob2.reset(100); Notice that the declaration of a counter object and the references to upperbound and lowerbound are qualified by CounterNameSpace. However, once an object of type counter has been declared, it is not necessary to further qualify it or any of its members. Thus, ob1.run( ) can be called directly; the namespace has already been resolved. CounterNameSpace::lowerbound = 90; do { i = ob2.run(); cout << i << " "; } while(i > CounterNameSpace::lowerbound); return 0; } 0 9 8 7 6 5 4 3 2 1 0 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 100 99 98 97 96 95 94 93 92 91 90
  翻译: