All (OOPS)
All (OOPS)
Introduction
Thinking in Objects
• You can walk into a computer store and, with a
little background and often some help, assemble
an entire PC from various components: a
motherboard, a CPU chip, a video card, a hard
disk, a keyboard, and so on.
• Ideally, when you finish assembling all the various
self-contained units, you have a system in which
all the units work together to create a larger
system with which you can solve the problems
you bought the computer for in the first place.
• Internally, each of those components may be
vastly complicated and engineered by
different companies with different methods of
design. But you don't need to know how the
component works, what every chip on the
board does, or how, when you press the ‘A’
key, an ‘A’ gets sent to your computer. As the
assembler of the overall system, each
component you use is a self-contained unit,
and all you are interested in is how the units
interact with each other.
• Will this video card fit into the slots on the
motherboard, and will this monitor work with
this video card?
• Will each particular component speak the right
commands to the other components it interacts
with so that each part of the computer is
understood by every other part?
• Once you know what the interactions are
between the components and can match the
interactions, putting together the overall system
is easy.
What does this have to do with
programming?
Everything.
Object-oriented programming works in exactly
this same way. Using object-oriented
programming, your overall program is made
up of lots of different self-contained
components (objects), each of which has a
specific role in the program and all of which
can talk to each other in predefined ways.
Problem Statement
Dominos made orders on behalf of registered
customer. An order consists of a number of
items. The order is either pending or serviced.
The following are the set of requirements
regarding placed and serviced orders:
1. An order may be placed by registered
customer.
2. A single customer may place a number of
orders.
3. An order may be deleted or edited before
being serviced.
4. An order must include at least one item (No
null order).
5. The desired quantity of an placed item must
not be null.
6. An order is serviced only after receiving
payment from a customer.
7. The customer can pay by cash or by card.
8. An invoice is made at the time of servicing the
order.
Contents
• Basic Concepts of C++
• Difference between C and C++
• Applications of C++
• How a program is Compiled?
• Simple C++ Program
Basic Concepts of C++
Basic Concepts of C++
• Basic Concepts:
• Objects
• Classes
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Objects
• Basic runtime entity in an object – oriented system.
• Often termed as “instance” of a class.
• Example:
– a person, a place, a bank account etc.
• They can be of any type based on its declaration.
• When program is executed, objects interact by sending messages
at runtime.
• Example 2:
– Two objects namely, “customer”, “account”. Customer object
may send a message to the account object requesting for bank
balance.
Classes
• Class is a collection of objects of similar type.
• Class is a way to bind the data and its associated functions
together.
• Objects are basically variable of the class or an object is an
instance of a class.
• Examples:
– Shape is a class and Rectangle, Square, Triangle are its objects.
–
Abstraction
• Providing only essential information to the outside world i.e. to
represent the needed information in program without presenting the
details.
• Data abstraction is a programming/ design technique that relies on
the separation of interface and implementation.
• In C++, they provide sufficient public methods to the outside world
to play with the functionality of the object and to manipulate object
data, i.e., state without actually knowing how class has been
implemented internally.
• The loader then puts together all of the executable object files
into memory for execution.
g++ -S prog1.cpp
g++ -c prog1.cpp
• Short-circuit evaluation
– (x >= 0) && (y > 1)
– Be careful with increment operators!
• (x > 1) && (y++)
– do-while
• Least flexible
• Always executes loop body at least once
– for
• Natural "counting" loop
while Loops Syntax
do-while Loop Syntax
while Loop Example
• Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
– Loop body executes how many times?
do-while Loop Example
count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition
▪ Declaration of constructor
▪ Default Constructor
▪ Parameterized Constructor
▪ This is achieved by passing arguments to the constructor function when the objects
are created.
▪ The constructors that can take arguments are called parameterized constructors.
Example of Parameterized Constructor
1. class example{
2. private:
3. int a;
4. public: When a constructor is paramete
5. example(int); //Parameterized Constructor must pass the initial values as arg
6. void display( ); the constructor function when an
declared.
7. };
8. example::example(int x){
9. a = x; Two ways Calling:
10.} • 1. Explicit
11.void example::display(){ • example e1 = exam
12. cout<<a<<"\n"; • 2. Implicit
13.} • example e1(5);
• //Shorthand metho
Example 2
1. #include <iostream>
2. using namespace std; 14.int main(){
3. class myclass { 15. myclass ob(3, 5);
4. int a, b; 16. //You can also pass
5. public: arguments as
6. myclass(int i, int j){ 17. // myclass ob=myclass
ob(3, 5);
7. a=i;
18. ob.show();
8. b=j;
19. return 0;
9. }
20.}
10.void show() {
11. cout << a << " " << b;
12. }
13.};
Constructors with Default Arguments
➢ The default argument constructor can be called with either one argument or no
arguments.
▪ The constructor can also be used to allocate memory while creating objects.
▪ This enables the system to allocate the right amount of memory for each object when
the objects are not of the same size.
class A
▪ The destructor is called {
automatically by the compiler when public:
the object goes out of scope. ~A(); //Destructor declaration
};
Thapar University 50
Example 2
1. #include <iostream> 7. int main(){
2. using namespace std; 8. // initialize a before
3. class shared { creating any objects
4. public: 9. shared::a = 99;//public
5. static int a; 10. cout << "This is initial
6. } ; value of a: " << shared::a;
11. cout << "\n";
12. shared x;
13. cout << "This is x.a: " <<
x.a;
14. return 0;
15.}
Uses
• Provide access control of shared resource used by all the
objects of a class, e.g. writing a file.
• Note:
54
Contd…
1. #include<iostream> 18.int shared :: resource;
2. using namespace std; 19.int main(){
3. class shared{ 20. shared o1, o2;
4. static int resource; 21. if(o1.getResource())
22. cout << "\no1 has resource.";
5. public:
23. if(!shared :: getResource())
6. static int getResource(){ 24. cout << "\no2 access denied.";
7. if(resource) 25. o1.freeResource();
8. return 0; 26. if(shared :: getResource())
9. else{ 27. cout << "\no2 has resource.";
10. resource = 1; 28. return 0;
11. return 1; 29.}
12. }
13. }
14. void freeResource(){
15. resource = 0;
16. }
17. };
55
Uses
56
Example
1. #include <iostream> 13. int static_type::i; // define i
2. using namespace std; 14. int main(){
3. class static_type { 15. // init static data before object
4. static int i; creation
5. public: 16. static_type::init(100);
6. static void init(int x) { 17. static_type x;
7. i = x; 18. x.show(); // displays 100
8. } 19. return 0;
9. void show() { 20. }
10. cout << i;
11. }
12. };
57
Thank You!
Lecture 4-7
Classes and Objects
Contents
• Encapsulation
Creating Objects:
item x;
• Public
• Protected
Access Specifier: Public
int x; // Global x
int main() {
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Scope Resolution Operator
3. To access a class’s static variables
class Test {
static int x;
public:
static int y;
void func(int x) { // We can access class's static variable even if there is a local variable
cout << "Value of static x is " << Test::x;
cout << "\nValue of local x is " << x;
}
};
int Test::x = 1; // In C++, static members must be explicitly defined like this
int Test::y = 2;
int main() {
Test obj;
int x = 3 ;
obj.func(x);
cout << "\nTest::y = " << Test::y;
return 0;
}
Scope Resolution Operator
• a is an integer array.
class array • It is declared as a private data
{ int a[10]; member of the class array.
public: • Can be used in class member
functions.
void setVal();
void sort();
void display();
}; 2
Example
1. #include<iostream>
2. using namespace std;
3. class array
4. { int a[10];
5. public:
6. void setVal()
7. { for (int i = 0; i < 10; i++)
8. cin >> a[i]; }
9. void sort()
10. { for (int i = 0; i < 9; i++)
11. for (int j = 0; j < 10 - i - 1; j++)
12. { if (a[j] > a[j + 1])
13. { a[j] = a[j] + a[j + 1];
14. a[j + 1] = a[j] - a[j + 1];
15. a[j] = a[j] - a[j + 1]; } } }
3
Contd…
5
Contd…
6
Contd…
• An array of objects is stored similar to multi-dimensional array.
emp manager[3];
name
manager[0]
age
name
manager[1]
age
name
manager[2]
age
7
Example
1. #include<iostream>
2. using namespace std;
3. class emp
4. { char name[10];
5. int age;
6. public:
7. void getData();
8. void putData();
9. };
10. void emp :: getData()
11. { cout << "Enter Name: "; cin >> name;
12. cout << "Enter Age: "; cin >> age; }
13. void emp :: putData()
14. { cout << "\tName: " << name << "\tAge: " << age << endl; }
8
Contd…
15. int main()
16. { emp manager[3];
17. for (int i = 0; i < 3; i++)
18. { cout << "\nEnter details of manager " << i + 1 << endl;
19. manager[i].getData();
20. }
21. for (int i = 0; i < 3; i++)
22. { cout << "\nManager " << i + 1;
23. manager[i].putData();
24. }
25. return 0;
26. }
9
Output
Enter details of manager 1
Enter Name: Arun
Enter Age: 50
10
Objects as function arguments
• Object can be passed as a function argument, like any other data
type to member functions as well as non-member functions.
• Pass-by-value
• Pass-by-reference
11
Example 1
1. #include <iostream> Output:
2. using namespace std;
3. class Convert Value of i in member function : 6
4. { public : Value of i in main : 3
5. int i;
6. void increment(Convert obj)
7. { obj.i=obj.i*2;
8. cout << "Value of i in member function : " << obj.i;
9. }
10. };
11. int main ()
12. { Convert obj1;
13. obj1.i=3; obj1.increment(obj1);
14. cout << "\nValue of i in main : " << obj1.i << "\n";
15. return 0; } 12
Example 2
#include <iostream> int main()
using namespace std; {
class myclass { myclass o(1);
int i; f(o);
public: cout << "This is i in main: ";
myclass(int n); cout << o.get_i() << "\n";
~myclass(); return 0;
void set_i(int n) { i=n; } }
int get_i() { return i; } void f(myclass ob)
}; {
myclass::myclass(int n) ob.set_i(2);
{ cout << "This is local i: " << ob.get_i();
i = n; cout << "\n";
cout << "Constructing " << i << "\n"; } Output
} Constructing 1
myclass::~myclass() This is local i: 2
{ Destroying 2
cout << "Destroying " << i << "\n"; This is i in main: 1
} Destroying 1
void f(myclass ob);
Example 3 (Pass-by-reference)
1. #include <iostream> Output:
2. using namespace std;
3. class Convert Value of i in member function : 6
4. { public : Value of i in main : 6
5. int i;
6. void increment(Convert &obj)
7. { obj.i=obj.i*2;
8. cout << "Value of i in member function : " << obj.i;
9. }
10. };
11. int main ()
12. { Convert obj1;
13. obj1.i=3; obj1.increment(obj1);
14. cout << "\nValue of i in main : " << obj1.i << "\n";
15. return 0; } 14
Returning Objects
Example 1
#include <iostream> cout << o.get_i() << "\n";
using namespace std; return 0;
class myclass { }
int i;
public: myclass f()
void set_i(int n) { i=n; } {
int get_i() { return i; } myclass x;
}; x.set_i(1);
myclass f(); //return object of return x;
type myclass }
int main()
{ Output:
myclass o;
o = f(); 1
16
• Dynamic Memory Allocation
• Reference Variables
5/5/2025 17
Dynamic Allocation Operators
• new
– Allocates memory and returns a pointer to the start of it. Let p_var
is a pointer variable of any data type type, then
p_var = new type;
• delete
– Frees memory previously allocated using new.
delete p_var;
5/5/2025 18
Operator new Syntax
new DataType
ptr
20
The NULL Pointer
• There is a pointer constant called the “null pointer”
denoted by NULL
• But NULL is not memory address 0.
• NOTE: It is an error to dereference a pointer
whose value is NULL. Such an error may cause your
program to crash, or behave erratically. It is the
programmer’s job to check for this.
delete Pointer
delete [ ] Pointer
*ptr = ‘B’;
5000
cout << *ptr;
‘B’
delete ptr; NOTE:
delete deallocates the
memory pointed to by ptr
23
Example
char *ptr ;
3000
ptr
ptr = new char[ 5 ]; ???
NULL
6000
???
24
Example
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int *p;
6. p = new int(87);
7. cout << "Value is: " << *p;
8. delete p;
9. return 0;
10.}
5/5/2025 25
Some points…
• In case of insufficient memory, new returns null pointer.
• So check for the pointer produced by new before using it.
…..
…..
p = new int;
If(!p)
count << "Allocation failed\n";
…..
…..
5/5/2025 26
Allocating Arrays
Allocate arrays using new by using :
p_var = new array_type [size];
Here, size specifies the number of elements in the
array.
5/5/2025 27
Example
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p, i;
p= new int[10];
for(i=0; i<10; i++ )
p[i] = i;
for(i=0; i<10; i++)
cout << p[i] << " ";
delete [] p; // release the array
return 0;
}
5/5/2025 28
Allocating Objects
• Allocate objects dynamically by using new.
• An object is created and a pointer is returned to
it.
• The dynamically created object acts just like any
other object. When it is created, its constructor
function (if it has one) is called.
• When the object is freed, its destructor function
is executed.
5/5/2025 29
Example
#include <iostream> int main()
#include <new> {
#include <cstring>
using namespace std; balance *p;
class balance { char s[80];
double cur_bal; double n;
char name[80];
public: p=new balance;
void set(double n, char *s) { p->set(12387.87, "Ralph
cur_bal = n; Wilson");
strcpy(name, s); p->get_bal(n, s);
}
void get_bal(double &n, char *s) cout << s << "'s balance is: " <<
{ n;
n = cur_bal; cout << "\n";
strcpy(s, name); delete p;
}
}; return 0;
}
5/5/2025 30
Advantages
• Automatically computes size of the data object, no need to use sizeof
operator.
• Automatically returns correct pointer type, no need to use type cast.
• Possible to initialize the object during the memory space creation.
• New and delete can be overloaded.
5/5/2025 31
Reference variable
• It provides an alias, an alternative name, for a previously defined
variable.
• Syntax:
data-type &reference-name = variable-name
• Must be initialized at the time of declaration.
• Example:
int x; int n[10];
int *p = &x; int &x = n[10];
int &m = *p; char &a = '\n';
5/5/2025 32
Reference Variables
Reference variable = alias for another variable
- Contains the address of a variable (like a pointer)
- No need to perform any dereferencing (unlike a pointer)
- Must be initialized when it is declared
int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5
z = 9; // same as x = 9;
33
Why Reference Variables
• Are primarily used as function parameters
34
Example 1
#include <iostream>
void p_swap(int *a, int *b)
Using namespace std; {
// Function prototypes
(required in C++) int temp;
temp = *a; (2)
void p_swap(int *, int *); *a = *b; (3)
*b = temp;
void r_swap(int&, int&);
}
int main (void){
void r_swap(int &a, int &b)
int v = 5, x = 10;
{
cout << v << x << endl;
int temp;
p_swap(&v,&x);
temp = a; (2)
cout << v << x << endl;
a = b; (3)
r_swap(v,x); b = temp;
cout << v << x << endl; }
return 0;
} 35
Example 2
1. #include <iostream>
2. using namespace std;
3. int main()
4. { int a = 10;
5. int &ref = a;
6. cout << a << " " << ref << endl;
7. ref += 5;
8. cout << a << " " << ref << endl;
9. return 0;
10.}
5/5/2025 36
Example 3
1. #include<iostream>
2. using namespace std;
3. void add(int &n);
4. int main()
5. { int number;
6. number = 34;
7. cout << " The initial value of number : " << number << endl;
8. add(number);
9. cout << " The final value of number : " << number << endl;
10. return(0); }
11. void add(int &n)
12. { n = n + 6; }
5/5/2025 37
Restrictions to References
• Reference to another reference is not possible.
• Address of a reference cannot be obtained.
• Arrays of references cannot be created.
• Pointer to a reference cannot be created.
• Reference for a bit-field is not possible.
• A reference variable must be initialized when it is declared unless it is
a member of a class, a function parameter, or a return value.
• Null references are prohibited.
5/5/2025 38
• Pointers to Objects
• this Pointer
• Pointers to class members
5/5/2025 39
Pointers to Objects
5/5/2025 43
Example 1
5/5/2025 44
Example 2
1. #include<iostream>
2. #include<cstring>
3. using namespace std;
4. class person
5. { char name[20];
6. int age;
7. public:
8. void setData(const char *s, int a)
9. { strcpy(name, s);
10. age = a; }
11. person& greater(person &x)
12. { if(x.age >= age) return x;
13. else return *this; }
14. void display()
15. { cout << name << " with age " << age; }
16. };
5/5/2025 45
Contd…
17. int main()
18. { person p1,p2,p3;
19. p1.setData("Abha", 21);
20. p2.setData("Akhil", 29);
21. p3.setData("Mitali", 31);
22. person p = p1.greater(p2);
23. cout << "Elder person is: ";
24. p.display();
25. p = p2.greater(p3);
26. cout << endl << "Elder person is: ";
27. p.display(); Output
28. return 0;
29. } Elder person is: Akhil with age 29
Elder person is: Mitali with age 31
5/5/2025 46
Pointers to Class Members
• A special type of pointer that "points"
generically to a member of a class, not to a
specific instance of that member in an object.
• This sort of pointer is called a pointer to a class
member or a pointer-to-member.
• A pointer to a member is not the same as a
normal C++ pointer. Instead, a pointer to a
member provides only an offset into an object
of the member's class at which that member
can be found.
5/5/2025 47
Contd…..
• Since member pointers are not true pointers, the . and -> cannot be
applied to them.
• To access a member of a class given a pointer to it, use the special
pointer-to-member operators .* and –>*.
• Their job is to allow you to access a member of a class given a pointer
to that member.
5/5/2025 48
Declaring and Assigning Pointer to Data Members of a
Class
5/5/2025 49
Accessing Data Members Using Pointers
5/5/2025 50
Example
#include<iostream> int main()
using namespace std; {
class Test Test t;
{ int Test :: *ptr=&Test::x;
public : t.*ptr=20;
int x; t.show_data();
void show_data(); Test *tp= new Test;
}; tp->*ptr=80;
void Test :: show_data() tp->show_data();
{ return 0;
cout<<“\n x=“<<x; } Output
} X=20
X=80
5/5/2025 51
Pointer to member function
5/5/2025 52
Example 1
int main()
#include <iostream> {
using namespace std; // declare pointer to data member
class X
{
int X::*ptiptr = &X::a;
public: // declare a pointer to member
int a; function
void f(int b) void (X::* ptfptr) (int) = &X::f;
{ // create an object of class type X
cout << "The value of b is "<< b << endl; X xobject;
} // initialize data member
};
xobject.*ptiptr = 10;
cout << "The value of a is " <<
xobject.*ptiptr << endl;
// call member function
(xobject.*ptfptr) (20);
}
Output
The value of a is 10
5/5/2025 53
The value of b is 20
Example 2
#include <iostream> data = &cl::val; // get offset of
using namespace std; val
class cl func = &cl::double_val; // get
{ offset of double_val()
public: cout << "Here are values: ";
cl(int i) { val=i; } cout << ob1.*data << " " <<
int val; ob2.*data << "\n";
int double_val() cout << "Here they are doubled:
{ return val+val; } ";
}; cout << (ob1.*func)() << " ";
int main() cout << (ob2.*func)() << "\n";
{ return 0;
int cl::*data; // data member }
pointer
int (cl::*func)(); // function
member pointer Output
cl ob1(1), ob2(2); // create objects Here are values: 1 2
Here they are doubled: 2 4
5/5/2025 54
Thank You!
55
1. const Member Function
2. Static Object
3. Copy constructor
‘const’ member function
int main(){
const int i = 10;
const int j = i + 10; // works fine
i++; // this leads to Compile time error
}
Const class variable
class Test{
const int i;
public:
Test(int x):i(x) {} //initialized using constructor
void show(){cout<<"i="<<i<<endl;}
};
int main(){Test t(190);t.show(); }
Const function
• The idea of const functions is not to allow
them to modify the object on which they are
called.
• It is recommended to make as many functions
const as possible so that accidental changes to
objects are avoided.
Const class member function
class A{
public: int x;
void func() const{
x = 0; // [Error] can’t modify
object variable
}
};
int main(){}
void Date::setMonth( int mn )
// constant_member_function {
#include<iostream> month = mn; // Modifies data member
using namespace std; }
class Date int main()
{ {
public: Date MyDate( 7, 4, 1998 );
Date( int mn, int dy, int yr ) const Date BirthDate( 1, 18, 1953 );
{ MyDate.setMonth(4); // Okay
month = mn; cout<<MyDate.getMonth();
day = dy; cout<<BirthDate.getMonth(); // Okay
year = yr; //BirthDate.setMonth( 4 ); // C2662 Error
} }
int getMonth() const; // A read-only function
void setMonth( int mn ); // A write function; can't be const
private:
int month,day,year;
};
#include<iostream> main()
using namespace std; {
class integer integer n1(10,20);
{ integer n2= integer(20,30);
int m,n; n1.display();
public: n2.display();
integer(int , int); }
display();
{ 1. Explicit
cout<<m<<n; integer n2 = example(20,30);
} 2. Implicit
}; integer n1(10,20);
integer :: integer(int x, int y) //Shorthand method
{
m=x; n=y;
}
Copy Constructor
1
Inheritance
• Inherit Definition -
Derive quality and characteristics from parents or ancestors. Like
you inherit features of your parents.
• Example:
"She had inherited the beauty of her mother"
• Inheritance in Object Oriented Programming can be described as a
process of creating new classes from existing classes.
2
Inheritance (Cont…)
• New classes inherit some of the properties and behaviour of
the existing classes.
• The existing class that is "parent" of a new class is called a base
class.
• New class that inherits properties of the base class is called
a derived class(“child class”).
• Inheritance is a technique of code reuse.
3
Example: Insect Taxonomy
4
The "is a" Relationship
• Inheritance establishes an "is a" relationship between classes.
– A poodle is a dog
– A car is a vehicle
– A flower is a plant
– A football player is an athlete
5
Base Class access control
• Derived class can be declared from a base
class with different access control, i.e., public
inheritance, protected inheritance or private
inheritance.
6
Protected Members and Class Access
7
Class Access Specifiers
public – object of derived class can be treated as object of base
class (not vice-versa)
protected – more restrictive than public, but allows derived
classes to know details of parents
private – prevents objects of derived class from being treated as
objects of base class.
8
Syntax
1. #include <iostream>
2. using namespace std;
3. class base
4. { .... ... .... };
5. class derived : access_specifier base
6. { .... ... .... };
10
Observations
• base class has three member variables: x, y and
z which are public, protected and private
member respectively.
• publicDerived inherits variables x and y as
public and protected. z is not inherited as it is a
private member variable of base class.
• protectedDerived inherits variables x and y.
Both variables become protected. z is not
inherited.
11
Observations (Cont…)
• If we derive a class
derivedFromProtectedDerived from
protectedDerived, variables x and y are also
inherited to the derived class.
• privateDerived inherits variables x and y. Both
variables become private. z is not inherited
• If we derive a class derivedFromPrivateDerived
from privateDerived, variables x and y are not
inherited because they are private variables of
privateDerived.
12
Accessibility in Public Inheritance
13
Accessibility in Protected Inheritance
14
Accessibility in Private Inheritance
15
Inheritance vs. Access
How inherited base class
members
Base class members appear in derived class
private: x private x is inaccessible
protected: y base class
private: y
public: z private: z
17
Inheritance vs. Access
class Grade class Test : protected Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
protected class access, it public members:
Test(int, int);
looks like this: protected members:
void setScore(float);
float getScore();
float getLetter();
18
Inheritance vs. Access
class Grade class Test : private Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
private class access, it void setScore(float);
float getScore();
looks like this: float getLetter();
public members:
Test(int, int);
19
What Does a Child Have?
An object of the derived class has:
• all members defined in child class
• all members declared in parent class
20
Types of Inheritance
21
Thanks
22
Types of Inheritance
23
Single Inheritance
• Single Inheritance: It is the inheritance
hierarchy wherein one derived class inherits
from one base class.
24
Single Inheritance Syntax
25
Single Inheritance Example
1. #include <iostream.h>
2. using namespace std;
3. class Shape { Output
4. protected:
5. int width;
6. int height;
7. public:
8. void setWidth(int w) {
9. width = w; }
10. void setHeight(int h) {
11. height = h; } } ;
12. class Rectangle: public Shape {
13. public:
14. int getArea() {
15. return (width * height); } }
16. int main {
17. Rectangle Rect;
18. Rect.setWidth(5);
19. Rect.setHeight(7);
20. cout << "Total area: " << Rect.getArea() << endl; // Print the area of the object.
21. return 0;
22. }
26
#include <iostream.h> int main()
using namespace std; {
class base { derived ob(3);
int i, j; ob.set(1, 2); // access member of
public: base
void set(int a, int b) ob.show(); // access member of
{ i=a; j=b; } base
void show() ob.showk(); // uses member of
derived class
{ cout << i << " " << j << "\n"; } return 0;
}; }
class derived : public base {
int k;
public:
derived(int x) { k=x; }
void showk() { cout << k << "\n";
}
};
27
// This program won't public:
compile. derived(int x) { k=x; }
#include <iostream.h> void showk()
using namespace std; { cout << k << "\n"; }
class base { };
int i, j; int main()
public: {
void set(int a, int b) { i=a; j=b; derived ob(3);
} ob.set(1, 2);
void show() { cout << i << " " // error, can't access set()
<< j << "\n";}
}; ob.show();
// Public elements of base are // error, can't access show()
private in derived. return 0;
class derived : private base { }
int k;
28
Multiple Inheritance
• Multiple Inheritance: It is the inheritance
hierarchy wherein one derived class inherits
from multiple base class(es).
29
Syntax
30
Inheriting Multiple Base Classes
#include <iostream> // Inherit multiple base classes.
using namespace std; class derived: public base1, public
class base1 { base2 {
protected: public:
int x; void set(int i, int j) { x=i; y=j; }
public: };
void showx() { cout << x << "\n"; } int main()
}; {
class base2 { derived ob;
protected: ob.set(10, 20);
int y; // provided by derived
Public: ob.showx(); // from base1
void showy() {cout << y << "\n";} ob.showy(); // from base2
}; return 0;
}
31
//EXAMPLE // Derived class
#include <iostream.h> class Rectangle: public Shape, public
using namespace std; PaintCost {
// Base class Shape
public:
class Shape {
public: int getArea() {
void setWidth(int w) { return (width * height);
width = w; } } };
void setHeight(int h) { int main(void) {
height = h; }
Rectangle Rect;
protected:
int width; int area;
int height; Rect.setWidth(5);
}; Rect.setHeight(7);
// Base class PaintCost area = Rect.getArea();
class PaintCost {
// Print the total cost of painting
public:
int getCost(int area) { cout << "Total paint cost: $" <<
return area * 70; Rect.getCost(area) << endl;
}}; return 0; }
32
Multilevel Inheritance
• Multilevel Inheritance: It is the inheritance
hierarchy wherein subclass acts as a base class
for other classes.
33
Syntax
34
Multi-level Inheritance
#include <iostream> //derived2 class
using namespace std; class derived2 : public derived
//Base class { public:
class base { void display3(){
public: cout << "\n2nd Derived class
void display1() { content.";
cout << "\nBase class content."; } } };
}; int main()
//derived class {
class derived : public base derived2 D;
{ D.display3();
public: D.display2();
void display2() D.display1();
{ return(0);
cout << "1st derived class content."; }
} };
35
Hierarchical Inheritance
• Hierarchical Inheritance: It is the inheritance
hierarchy wherein multiple subclasses inherit
from one base class.
36
Hierarchical Inheritance
37
Hierarchical Inheritance
#include <iostream> void disp() {
#include <string.h> cout << "Age: " << age <<
using namespace std; endl; cout << "Gender: "
//Base Class << gender << endl; }
class member { };
char gender[10]; //derived from member
int age; class stud : public member
public: { char level[20];
void get() public:
{ cout << "Age: "; cin >> age; void getdata() {
member::get();
cout << "Gender: "; cin >> cout << "Class: ";
gender; }
cin >> level; }
Continue...
38
void disp2() void disp3() {
{ member::disp(); member::disp();
cout << "Level: " << level; cout << "Salary: Rs." <<
} }; salary << endl;
//staff class derived from } };
member
class staff : public member int main() {
{ float salary; //member M;
public: staff S;
void getdata() { stud s;
member::get(); s.getdata();
cout << "Salary: Rs."; s.disp();
cin >> salary; } S.getdata();
S.disp();
return(0); }
39
Hybrid Inheritance
• Hybrid Inheritance: The inheritance hierarchy
that reflects any legal combination of other
four types of inheritance.
40
Syntax
41
#include <iostream> class D : public B, public C
using namespace std; //D is derived from class B and
class A { class C
public: int x; { public:
}; void sum()
class B : public A { { cout << "Sum= " << x + y; }
public: B() //constructor to };
initialize x in base class A int main()
{ x = 10; } { D obj1; //object of derived
}; class D
class C { obj1.sum();
public: int y; C() //constructor to return 0; Output
initialize y { y = 4; } }
};
42
Thanks
43
Inheritance - 2
1
Content
• Constructor and Destructor in Inheritance
• Inheritance and Static Functions
• Virtual class
• Abstract Class
• Pure Virtual Functions
Constructors and Destructors in Base and
Derived Classes
• Derived classes can have their own constructors and destructors.
• When an object of a derived class is created, the base class’s
constructor is executed first, followed by the derived class’s
constructor.
• When an object of a derived class is destroyed, its destructor is called
first, then that of the base class.
3
//EXAMPLE ~derived()
#include<iostream> { cout << "Destructing derived\n"; }
Using namespace std; };
//base class int main()
class base { {
public: derived ob;
base() // do nothing but construct and
{ cout << "Constructing base\n"; } destruct ob
return 0;
~base()
{ cout << "Destructing base\n"; } }
};
//derived class
class derived: public base { Program Output
public: Constructing base
Constructing derived
derived()
Destructing derived
{ Destructing base
cout << "Constructing derived\n"; }
4
Constructors and Destructors with Multiple Base
Classes
• Constructors are called in order of derivation, left to right, as
specified in derived's inheritance list.
• Destructors are called in reverse order, right to left.
5
//MULTI-LEVEL class derived2: public derived1 {
#include <iostream> public:
using namespace std; derived2() { cout <<
class base { "Constructing derived2\n"; }
public: ~derived2() { cout <<
"Destructing derived2\n"; }
base() };
{ cout << "Constructing base\n"; int main()
}
~base() { cout << "Destructing {
base\n"; } derived2 ob;
}; // construct and destruct ob
class derived1 : public base { return 0;
public: } Program Output:
derived1() { cout << Constructing base
"Constructing derived1\n"; } Constructing derived1
~derived1() { cout << Constructing derived2
"Destructing derived1\n"; } Destructing derived2
}; Destructing derived1
Destructing base
6
//MULTIPLE BASE CASES class derived: public base1, public
#include <iostream> base2 {
using namespace std; public:
class base1 { derived() { cout << "Constructing
derived\n"; }
public: ~derived() { cout << "Destructing
base1() { cout << "Constructing derived\n"; }
base1\n"; } };
~base1() { cout << "Destructing int main()
base1\n"; }
}; {
class base2 { derived ob;
public: // construct and destruct ob
base2() { cout << "Constructing return 0;
base2\n"; } } Program Output:
Constructing base1
~base2() { cout << "Destructing Constructing base2
base2\n"; } Constructing derived
}; Destructing derived
Destructing base2
Destructing base1
7
Passing Arguments to Base Class Constructor
derived-constructor(arg-list) : base1(arg-list),
base2(arg-list),
// ...
baseN(arg-list)
{
// body of derived constructor
}
8
Order of Constructor Call
• Base class constructors are always called in the derived class
constructors.
• Whenever you create derived class object, first the base class default
constructor is executed and then the derived class's constructor
finishes execution.
9
//EXAMPLE // derived uses x; y is passed
#include <iostream> along to base.
using namespace std; derived(int x, int y): base(y)
class base { { j=x;
protected: cout << "Constructing
derived\n"; }
int i; ~derived() { cout << "Destructing
public: derived\n"; }
base(int x) void show() { cout << i << " " << j
<< "\n"; }
{ i=x; cout << "Constructing
base\n"; } };
~base() { cout << "Destructing int main()
base\n"; } {
}; derived ob(3, 4);
class derived: public base { ob.show(); // displays 4 3
int j; return 0;
public: }
10
//MULTIPLE BASE CASES class derived: public base1, public
#include <iostream> base2 {
int j;
using namespace std;
class base1 { public:
12
Here’s what actually happens when derived is instantiated:
• Memory for derived is set aside (enough for both the Base and
Derived portions)
• The appropriate Derived constructor is called
• The Base object is constructed first using the appropriate Base
constructor. If no base constructor is specified, the default
constructor will be used.
• The initialization list initializes variables
• The body of the constructor executes
• Control is returned to the caller
13
Points to note
• It is important to understand that arguments to a base-class
constructor are passed via arguments to the derived class' constructor.
• Even if a derived class‘ constructor does not use any arguments, it will
still need to declare one if the base class requires it.
• In this situation, the arguments passed to the derived class are simply
passed along to the base.
14
Why is Base class Constructor called inside Derived class?
• Constructors have a special job of initializing the object properly.
• A Derived class constructor has access only to its own class members,
but a Derived class object also have inherited property of Base class,
and only base class constructor can properly initialize base class
members.
• Hence all the constructors are called, else object wouldn't be
constructed properly.
15
// This program contains an int main() {
error and will not compile. derived3 ob;
#include <iostream> ob.i = 10; // this is
ambiguous, which i???
using namespace std;
ob.j = 20;
class base {
ob.k = 30;
public: int i; }; // i ambiguous here, too
class derived1 : public base { ob.sum = ob.i + ob.j + ob.k;
public: int j; }; // also ambiguous, which i?
class derived2 : public base { cout << ob.i << " ";
public: int k; }; cout << ob.j << " " << ob.k ;
class derived3 : public
cout << ob.sum;
derived1, public derived2 { return 0;
public: int sum; }; }
16
Discussion
• which ‘i’ is being referred to, the one in derived1 or the one in
derived2?
• Because there are two copies of base present in object ob, there are
two ob.is! ->, the statement is inherently ambiguous.
• There are two ways to remedy the preceding program.
• The first is to apply the scope resolution operator to i and manually
select one i. Example (on next slide).
17
// This program uses explicit int main()
scope resolution to select i. {
#include <iostream>
derived3 ob;
using namespace std;
ob.derived1::i = 10; // scope
class base { public: int i; }; resolved, use derived1's i
// derived1 inherits base. ob.j = 20;
class derived1 : public base { ob.k = 30;
public: int j; }; // scope resolved
// derived2 inherits base. ob.sum = ob.derived1::i + ob.j +
class derived2 : public base { ob.k;
public: int k; }; // also resolved here
class derived3 : public cout << ob.derived1::i << " ";
derived1, public derived2 { cout << ob.j << " " << ob.k << " ";
public: int sum; }; cout << ob.sum;
return 0; }
18
Discussion
• As you can see, because the :: was applied, the program has
manually selected derived1's version of base.
• What if only one copy of base is actually required? Is there some way
to prevent two copies from being included in derived3?
• This solution is achieved using virtual base classes.
20
• When two or more objects are derived from a common base class, you
can prevent multiple copies of the base class from being present in an
object derived from those objects by declaring the base class as virtual
when it is inherited.
• You accomplish this by preceding the base class' name with the
keyword virtual when it is inherited.
• For example, here is another version of the example program in which
derived3 contains only one copy of base:
21
// This program uses virtual base classes. int main()
#include <iostream>
using namespace std;
{
class base { public: int i; }; derived3 ob;
ob.i = 10; // now unambiguous
// derived1 inherits base as virtual.
ob.j = 20;
class derived1 : virtual public base { ob.k = 30;
public: int j; }; // unambiguous
// derived2 inherits base as virtual. ob.sum = ob.i + ob.j + ob.k;
// unambiguous
class derived2 : virtual public base { cout << ob.i << " ";
public: int k; };
cout << ob.j << " " << ob.k << " ";
class derived3 : public derived1, public cout << ob.sum;
derived2
{ public: int sum; }; return 0;
}
22
Discussion
• As you can see, the keyword virtual precedes the rest of the inherited
class‘specification.
• Now that both derived1 and derived2 have inherited base as virtual,
any multiple inheritance involving them will cause only one copy of
base to be present.
• Therefore, in derived3, there is only one copy of base and ob.i = 10 is
perfectly valid and unambiguous.
23
Inheritance and Static Functions
24
Virtual base class
• They are used to prevent the confusion or duplicity among child
classes during inheritance.
• Consider the following situation:
class A {
public: void show() {cout<<"In A"<<endl;}
};
int main(){
Dog obj; obj.sound(); obj.sleeping();
}
Output:
Woof
Sleeping
class Animal{
public:
virtual void sound() = 0;
void sleeping() {cout<<"Sleeping"; }
};
class Dog: public Animal{
public:
void sound() {cout<<"Woof"<<endl;}
};
int main(){
Animal *obj = new Dog;
obj->sound();
}
Output:
Woof
Abstract Class
• An abstract class is designed to act as base class. It is a design concept
in program development and provides a base upon which other
classes may be built.
• Abstract Class is a class which contains atleast one Pure Virtual
function in it. Abstract classes are used to provide an Interface for its
sub classes. Classes inheriting an Abstract Class must provide
definition to the pure virtual function, otherwise they will also
become abstract class.
34
Characteristics of Abstract Class
• Abstract class cannot be instantiated, but pointers and references of
Abstract class type can be created.
• Abstract class can have normal functions and variables along with a
pure virtual function.
• Classes inheriting an Abstract Class must implement all pure virtual
functions, or else they will become Abstract too.
35
Pure Virtual Functions
• Pure virtual Functions are virtual functions with no definition.
• They start with virtual keyword and ends with = 0.
• Syntax for a pure virtual function,
virtual void fun() = 0;
36
//Abstract base class int main()
class Base { {
public: //Base obj; (Compile Time
virtual void show() = 0; }; Error)
class Derived:public Base { Base *b;
public: Derived d;
void show() b = &d;
{ b->show();
cout << "Implementation of return 0;
Virtual Function in Derived }
class";
}
};
37
Note:
• Pure Virtual functions can be given a small definition in the Abstract
class, which you want all the derived classes to have. Still you cannot
create object of Abstract class.
• Also, the Pure Virtual function must be defined outside the class
definition. If you will define it inside the class definition, complier will
give an error. Inline pure virtual definition is Illegal.
38
Polymorphism
Contents
• Polymorphism
• Function Overloading
• Default Function Arguments
• Ambiguity in Function Overloading
Polymorphism
• The word polymorphism means having many
forms. In simple words, we can define
polymorphism as the ability of a message to
be displayed in more than one form.
{
return i*j;
}
Key Points
• The key point about function overloading is that the functions must differ in regard to the types
and/or number of parameters. Two functions differing only in their return types cannot be
overloaded.
• For example, this is an invalid attempt to overload myfunc( ):
int myfunc(int i);
float myfunc(int i);
// Error: differing return types are insufficient when overloading.
• Sometimes, two function declarations will appear to differ, when in
fact they do not. For example, consider the following declarations.
void f(int *p);
void f(int p[]); // error, *p is same as p[]
• Remember, to the compiler *p is the same as p[ ]. Therefore, although the two prototypes appear
to differ in the types of their parameter, in actuality they do not.
Example 3
Example 4
(Function overloading in classes)
Inheritance based Polymorphism
Example
Extend the Logic
Virtual Functions
• Be aware that the virtual function mechanism works only with
pointers to objects and, with references, not with objects themselves.
Class Activity (15 minutes)
• Can you showcase polymorphism (Drive function in various types
of automobiles) in context of VEHICLES ?
Overloading vs overriding
• Function overloading – same function name but
different arguments. Functions are defined in the
same class.
Also known as early or static binding Also known as late or dynamic binding
It executes faster because the function It executes slower because the function
is resolved at compilation time only. is resolved at Run-time.
int main()
{
cout << myfunc(10.1) << " "; // unambiguous, calls
myfunc(double)
cout << myfunc(10); // ambiguous
return 0;
}
Thanks
Operator Overloading
Introduction
• Operator overloading
➢ Enabling C++’s operators to work with class objects
➢ Using traditional operators with user-defined objects
➢ Examples of already overloaded operators
• Operator << is both the stream-insertion operator and the
bitwise left-shift operator
• Operator >> is both the stream-extraction operator and the
bitwise right-shift operator
➢ Compiler generates the appropriate code based on the
manner in which the operator is used.
Introduction (Cont…)
• Overloading an operator
– Write function definition as normal
– Functionname is keywordoperator followed bythe symbol for the
operator being overloaded
– For e.g., operator+ used to overload the addition operator
(+)
• Using operators
– To use an operator on a class object, it must be overloaded unless the
assignment operator (=) or the address operator (&)
• Assignment operator by default performs memberwise assignment
• Address operator (&) by default returns the address of an object
Restrictions on Operator Overloading
• Overloading restrictions
– Precedence of an operator cannot be changed
– Associativity of an operator cannot be changed
– number of operands cannot be changed
• Unary operators remain unary, and binary operators remain binary
• Operators &, *, + and - each have unary and binary versions
• Unary and binary versions can be overloaded separately
• No new operators can be created
– Use only existing operators
• No overloading operators for built-in types
– Cannot change how two integers are added
– Produces a syntax error
What are Operators in C++?
• Arithmetic Operators: +, −, /, ∗, %
• Assignment Operators: +=,+=, −=,−=, /=,/=, ∗=,∗=, %=%=
• Relational Operators: ==,==, !=,!=, >=,>=, <=,<=,etc.
• Logical Operators: &&,&&, ∣∣,∣∣, !!
• Bitwise Operators: &,&, ∣,∣, >>, <<etc.
• Other Operators: sizeof, ?:,etc.
Restrictions on Operator Overloading
• All the C++ operators can be overloaded except the following:
• Scope Resolution Operator (::)
• Conditional Operator (? :)
• Size Operator (sizeof)
• Class Member Access Operators (. and .*)
Operator Functions as Class Members vs. as friend Functions
Note: If left operand is of a different type than class, operator function must be a non-member function
C++ Syntax for Operator Overloading
• class ClassName{
•
• private:
• ...............
•
public:
• ...............
•
• <ReturnType> operator <operator> (arguments){
• ...............
• ...............
• }
• ...............
• };
Creating a Member Operator Function
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1; // activates operator-() function
D1.displayDistance(); // D1display Output:
-D2; // activates operator-() function F: -11 I:-10 F: 5 I:-11
D2.displayDistance(); // display D2
return 0;
}
Binary Operators
• The binary operators take two arguments.
• Given an object called obj, the expression obj[3] translates into this
call to the operator[ ]( ) function: obj.operator[](3)
Example 1
#include <iostream> int operator[](int i)
using namespace std; { return a[i];
class atype { }
int a[3]; };
public: int main()
atype(int i, int j, int k) { {
a[0] = i; atype ob(1, 2, 3);
a[1] = j; cout << ob[1]; // displays 2
a[2] = k; return 0;
} } Output:
2
Example 2
#include <iostream> int main()
using namespace std; {
class atype { atype ob(1, 2, 3);
int a[3]; cout << ob[1]; // displays 2
public: cout << " ";
atype(int i, int j, int k) { ob[1] = 25; // [] on left of =
a[0] = i; cout << ob[1]; // now displays 25
a[1] = j; return 0;
a[2] = k; }
}
Output:
int &operator[](int i) {
return a[i]; 2 25
}
};
Overloading ()
• When we overload the ( ) function call operator, we are
not creating a new way to call a function.
Example:
double operator()(int a, float f, char *s);
and an object O of its class, then the statement
O(10, 23.34, "hi");
translates into this call to the operator( ) function.
O.operator()(10, 23.34, "hi");
Example
#include <iostream>
using namespace std; // Overload + for loc
class loc { loc loc::operator+(loc op2)
int longitude, latitude; {
public: loc temp;
loc() {} temp.longitude = op2.longitude + longitude;
loc(int lg, int lt) temp.latitude = op2.latitude + latitude;
{ return temp;
longitude = lg; }
latitude = lt;
}
void show() { int main()
cout << longitude << " "; {
cout << latitude << "\n"; loc ob1(10, 20), ob2(1, 1);
} ob1.show();
loc operator+(loc op2); ob1(7, 8); // can be executed by itself
loc operator()(int i, int j); ob1.show();
}; ob1 = ob2 + ob1(10, 10); // can be used in expressions
// Overload ( ) for loc ob1.show();
loc loc::operator()(int i, int j) return 0;
{ }
longitude = i;
latitude = j;
return *this;
}
Overloading the Comma Operator
#include <iostream> cout << op2.longitude << " " << op2.latitude << "\n";
using namespace std; return temp;
class loc { }
int longitude, latitude; // Overload + for loc
public: loc loc::operator+(loc op2)
loc() {} {
loc(int lg, int lt) { loc temp;
longitude = lg; temp.longitude = op2.longitude + longitude;
latitude = lt; temp.latitude = op2.latitude + latitude;
} return temp;
void show() { }
cout << longitude << " "; int main()
cout << latitude << "\n"; {
} loc ob1(10, 20), ob2( 5, 30), ob3(1, 1);
loc operator+(loc op2); ob1.show();
loc operator,(loc op2); ob2.show();
}; ob3.show();
// overload comma for loc cout << "\n";
loc loc::operator,(loc op2) ob1 = (ob1, ob2+ob2, ob3);
{ ob1.show(); // displays 1 1, the value of ob3
loc temp; return 0;
temp.longitude = op2.longitude; }
temp.latitude = op2.latitude;
Overloading ->
• The –> pointer operator, also called the class member access operator,
is considered a unary operator when overloading.
➢ Using constructor
➢ Using Operator Overloading
Example (Using Constructor)
// Program to convert basic type to class type using constructor
int main()
#include <iostream>
{
using namespace std;
int duration;
class Time { cout<<"Enter time duration in minutes";
int hrs, min; cin>>duration;
public: Time t1=duration;
t1.display();
Time (int);
return 0;
void display(); }
};
Time :: Time (int t)
{
During type conversion using the
cout<<"Basic Type to ==> Class Type Conversion..."<<endl;
constructor we can pass only one
hrs=t/60;
argument and we can do type
min=t%60; conversion at the type of
} initialization only.
void Time::display()
{ cout<<hrs<< ": Hours(s)" <<endl; cout<<min<< " Minutes" <<endl;
}
Using Operator Overloading
• Type conversion from basic to class type can also be done by
operator overloading.
operator typename( )
{
//Function statements
}
Continued…
• The conversion function should satisfy the following condition:
int main() {
try {
throw 10;
}
catch (char *e) { cout << "Caught " << e; }
catch (...) { cout << "Default Exception\n"; }
return 0;
}
Output
Default Exception
// What will be the output?
int main() {
try {
throw "10";
}
catch (const char *e) { cout << "Caught " << e; }
catch (...) { cout << "Default Exception\n"; }
}
Output
Caught 10
Exception Specification
• C++ provides a mechanism to ensure that a given function is
limited to throw only a specified list of exceptions.
• A string is an
inbuilt C++ class
that contains a
char array but
automatically
manages it using
built in functions
Basic string program
#include <string>
#include<iostream>
using namespace std;
int main(){
string greeting ="Hello";
cout<<greeting;
}
String concatenation using ‘+’
• DevCpp may not have this file so either you can download and
include it using #include”bits/stdc++”
#include<iostream>
using namespace std;
int main(){
hash <char> hash_character; //syntax for char type
cout << "Hash key is: " << hash_character(‘a’);
}
Output
Hash key is: 97
#include<iostream>
using namespace std;
int main(){
hash <int> hash_int;
cout << "Hash key is: " << hash_int(597)<<endl;
cout << "Hash key is: " << hash_int(-597)<<endl;
}
Output
Hash key is: 597
Hash key is: 18446744073709551019
Looks like hash key for positive integer is same as its value and
for negative it is a complicated code (may be t’s compliment,
not sure)
// String hashing
#include<iostream>
using namespace std;
int main(){
hash <string> hash_string;
cout << "Hash key is: " << hash_string("a")<<endl;
cout << "Hash key is: " << hash_string("apple")<<endl;
}
Output
Hash key is: 4993892634952068459
For both “a” and “apple” the hash values are complicated
codes calculated internally.
Vector (another STL)
• Vector is a dynamic array with a size flexibility and direct
access to any element.
// Simple vector to insert int
values
#include<vector>
#include<iostream>
using namespace std;
int main() {
vector<int> v1;
v1.push_back(11);
v1.push_back(22);
vector<int>::iterator i;
for(i=v1.begin();i!=v1.end();++i)
cout << *i << endl;
}
Output
11
22
#include<algorithm> for vector functions
By including algorithm header file, many inbuilt
functions can be executed on vector such as: