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

More Related Content

PPT
Presentation
DOCX
DS Code (CWH).docx
PPTX
Presentations_PPT_ Unit-6_OOP.pptx
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
DOC
Brief Summary Of C++
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
ZIP
DOCX
Virtual function
Presentation
DS Code (CWH).docx
Presentations_PPT_ Unit-6_OOP.pptx
Object Oriented Programming (OOP) using C++ - Lecture 5
Brief Summary Of C++
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Virtual function

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

PDF
Imugi: Compiler made with Python
PPTX
Data structure and Algorithms (C++).pptx
PPT
Data structure and problem solving ch05.ppt
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
PPT
ch08.ppt
PPTX
Learn c++ (functions) with nauman ur rehman
PPT
Overloading
PPT
Link list
PPTX
Pointers, virtual function and polymorphism
PPT
CPP Language Basics - Reference
DOCX
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
PPTX
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
PDF
.NET 2015: Будущее рядом
PDF
polymorphism in c++ with Full Explanation.
PPT
Unit 6 pointers
PPTX
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
PPTX
C concepts and programming examples for beginners
PDF
#살아있다 #자프링외길12년차 #코프링2개월생존기
PDF
Start Wrap Episode 11: A New Rope
PPTX
Object Oriented Programming Using C++: C++ STL Programming.pptx
Imugi: Compiler made with Python
Data structure and Algorithms (C++).pptx
Data structure and problem solving ch05.ppt
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
ch08.ppt
Learn c++ (functions) with nauman ur rehman
Overloading
Link list
Pointers, virtual function and polymorphism
CPP Language Basics - Reference
#ifndef CRYPTO_HPP#define CRYPTO_HPP#include functional#.docx
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
.NET 2015: Будущее рядом
polymorphism in c++ with Full Explanation.
Unit 6 pointers
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
C concepts and programming examples for beginners
#살아있다 #자프링외길12년차 #코프링2개월생존기
Start Wrap Episode 11: A New Rope
Object Oriented Programming Using C++: C++ STL Programming.pptx
Ad

Recently uploaded (20)

PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Pharma ospi slides which help in ospi learning
PDF
Basic Mud Logging Guide for educational purpose
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Cell Types and Its function , kingdom of life
PPTX
master seminar digital applications in india
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
GDM (1) (1).pptx small presentation for students
Pharma ospi slides which help in ospi learning
Basic Mud Logging Guide for educational purpose
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Complications of Minimal Access Surgery at WLH
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Sports Quiz easy sports quiz sports quiz
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Cell Types and Its function , kingdom of life
master seminar digital applications in india
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
O5-L3 Freight Transport Ops (International) V1.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
01-Introduction-to-Information-Management.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
STATICS OF THE RIGID BODIES Hibbelers.pdf
Renaissance Architecture: A Journey from Faith to Humanism
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Microbial diseases, their pathogenesis and prophylaxis
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