際際滷

際際滷Share a Scribd company logo
CHAPTER 2
POLYMORPHISM
POINTERS
 Pointer is a derived data type that refers to the address of another variable.
A pointer variable tells that where to get the data instead of telling the
actual data.
 The declaration of the pointer is based on the data type of the variable it
points to.
data-type *pointer-variable
 At any point of time a pointer variable can point to only one data type.
int *ptr;
 Here ptr contains the memory location of any integer variable.
e.g. int *ptr , a; //Declaration
ptr=&a; //Initialization
int a = 25;
int *p;
p = &a;
cout<<"&a:"<<&a;
cout<<"p:"<<p;
cout<<"&p:"<<&p;
cout<<"*p:"<<*p;
cout<<"*(&a):"<<*(&a);
(*p)++;
cout<<"*p:"<<*p;
cout<<"a:"<<a;a
25 1000
p
a
1000 2000
int a = 25;
int *p,**s;
p = &a;
s = &p;
cout<<"n*p:"<<*p;
cout<<"n*s:"<<*s;
cout<<"n**s:"<<**s;
cout<<"n*(*(&p)):"<<*(*(&p));
cout<<"n***(&s):"<<***(&s);
POINTERS WITH ARRAYS
 Pointers are associated with arrays as:
 Pointers are useful to allocate arrays dynamically
 Efficient tools to access the elements of an array.
 We can declare pointers to arrays as ;
int *ptr;
ptr = number[0]; OR ptr = number;
 An array of Pointer is an array of addresses i.e all the elements of the Pointer
array points to an item of the data array. An array of Pointer is declared as
int *abc[10];
 It is an array of ten pointers ie. Addresses all of them points to an integer.
Before initializing they point to some unknown values in the memory space.
int main ()
{
int arr[5] = {10,20,30,40,50};
int *ptr;
ptr = &arr[0];
for ( int i = 0; i < 5; i++ )
{
cout <<"*(ptr+" << i <<"):";
cout <<*(ptr + i) << endl;
}
return 0;
}
POINTERS TO OBJECTS
 Just like pointers to normal variables and functions, we can
have pointers to class members (variables and methods).
class ABC
{
public:
int a=50;
};
int main()
{
ABC ob1;
ABC *ptr;
ptr = &ob1;
cout << ob1.a;
cout << ptr->a; //
Accessing members of
class with pointer
}
class demo{
int i;
public:
demo(int x){
i=x; }
int getdata(){
return i;}
};
int main()
{
demo d[3]={55,66,77};
demo *ptr=d; //similar to *ptr=&d[0]
for(int i=0;i<3;i++)
{
cout<<ptr->getdata()<<endl;
ptr++;
}
}
Practice Program
 Create a class student having private members marks,
name and public members rollno, getdata(),
printdata(). Demonstrate concept of pointer to class
members for array of 3 objects.
THIS POINTER
 this pointer represent an object that invoke or call a member
function.
 It will point to the object for which member function is called.
 It is automatically passed to a member function when it is
called.
 It is also called as implicit argument to all member function.
 Friend functions can not be accessed using this pointer,
because friends are not members of a class.
 Only member functions have a this pointer.
 A static member function does not have this pointer.
THIS POINTER
 Following are the situations where this pointer is used.
 When local variables name is same as members name
 To return reference to the calling object
class sample
{
int a,b;
public:
void input(int a,int b){
this->a = a + b;
this->b = a - b;
}
void output(){
cout<<"a = "<<a;
cout<<"b = "<<b;
}
};
int main()
{
sample ob1;
int a=5,b=8;
ob1.input(a,b);
ob1.output();
}
class Test
{
int x; int y;
public:
Test& setX(int a) { x = a; return *this; } //Reference to the calling object can be returned
Test& setY(int b) { y = b; return *this; }
void print() {
cout << "x = " << x ;
cout << " y = " << y;
}
};
int main()
{
Test obj1;
obj1.setX(10).setY(20); // chain function calls
obj1.print();
}
POINTERS TO DERIVED CLASS
 We can use pointers not only to the base objects but also to the objects of
derived classes.
 Pointers to the base classes are type-compatible to the objects of the derived
classes. Hence, A single pointer variable of base type can be made to point to
objects belonging to base as well as derived classes.
E.g. Here B is a base class, D is Derived class.
B *cptr;
B b;
D d;
cptr=&b;
we can also make the cptr to point to object d also.
cptr=&d;
As d is an object derived from the class B
POINTERS TO DERIVED CLASS
 We can access those members of derived class which are
inherited from base class by base class pointer.
 But we cannot access original member of derived class which
are not inherited from base class using base class pointer.
 We can access original member of derived class using pointer of
derived class.
VIRTUAL FUNCTIONS
 A virtual function is a member function that is declared within a base class
and redefined by a derived class.
 To create a virtual function, precede the function's declaration in the base
class with the keyword virtual.
 When virtual function accessed "normally," it behave just like any other type
of class member function. But when it is accessed via a pointer it supports
run time polymorphism.
 Base class and derived class have same function name and base class
pointer is assigned address of derived class object then also pointer will
execute base class function.
 After making virtual function, the compiler will determine which function to
execute at run time on the basis of assigned address to pointer of base class.
RULES FOR VIRTUAL FUNCTIONS
 The virtual functions must be member of any class.
 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another class.
 A virtual function in a base class must be defined, even though it may not be used.
 We cannot have virtual constructors, but we can have virtual destructors.
 The derived class pointer cannot point to the object of base class.
 When a base pointer points to a derived class, then also it is incremented or
decremented only relative to its base type. Therefore we should not use this method
to move the pointer to the next object.
 If a virtual function is defined in base class, it need not be necessarily redefined in
the derived class. In such cases, call will invoke the base class.
PURE VIRTUAL FUNCTIONS
 A pure virtual function is virtual function that has no definition within the base
class.
 A pure virtual function means do nothing function.
 We can say empty function. A pure virtual function has no definition relative
to the base class.
 Programmers have to redefine pure virtual function in derived class, because
it has no definition in base class.
 A class containing pure virtual function cannot be used to create any direct
objects of its own.
 This type of class is also called as abstract class.
PURE VIRTUAL FUNCTIONS
 Syntax:
virtual void display() = 0;
OR
virtual void display() {}
ABSTRACT CLASS
 A class that contains at least one pure virtual function is
called abstract class.
 You can not create objects of an abstract class, you can
create pointers and references to an abstract class.
VIRUTAL DESTRUCTOR
 Deleting a derived class object using a pointer of base class
type that has a non-virtual destructor results in undefined
behavior. To correct this situation, the base class should be
defined with a virtual destructor.
 Making base class destructor virtual guarantees that the
object of derived class is destructed properly, i.e., both base
class and derived class destructors are called.
CHAPTER 2
TEMPLATES
INTRODUCTION
 C++ templates are a powerful mechanism for code reuse,
as they enable the programmer to write code that
behaves the same for any data type.
 By template we can define generic classes and functions.
 In simple terms, you can create a single function or a class
to work with different data types using templates.
 It can be considered as a kind of macro. When an object
of a specific type is defined for actual use, the template
definition for that class is substituted with the required data
type.
TEMPLATES
TEMPLATES
FUNCTION TEMPLATE CLASS TEMPLATE
FUNCTION TEMPLATE
 A function template specifies how an individual function can
be constructed.
 We write a generic function that can be used for different data
types.
 Syntax:
template <class T>
T functionname(T arg1,T arg2)
{
function body;
}
 A generic function defines a general set of operations that will be applied to
various types of data.
 A generic function has the type of data that it will operate upon passed to
it as a parameter.
 Using this mechanism, the same general procedure can be applied to a
wide range of data.
 For example the Quicksort algorithm is the same whether it is applied to an
array of integers or an array of floats. It is just that the type of data being
sorted is different.
 By creating a generic function, you can define, independent of any data,
the nature of the algorithm.
 Once this is done, the compiler automatically generates the correct code
for the type of data that is actually used when you execute the function.
 In essence, when you create a generic function you are creating a function
that can automatically overload itself.
 A generic function is also called a template function. When the compiler
creates a specific version of the function, it is said to have created a
generated function.
 Generic functions may be overloaded.
Suppose you write a function printData:
void printData(int value){
cout<<"The value is "<<value;
}
Now if you want to print double values or string values, then you have to
overload the function:
void printData(float value){
cout<<"The value is "<<value;
}
void printData(char *value) {
cout<<"The value is "<<*value;
}
To perform same operation with different data type, we have to write same
code multiple time.
C++ provides templates to reduce this type of duplication of code.
template<class T>
void printData(T value){
cout<<"The value is "<<value;
}
We can now use printData for any data type. Here T is a template parameter
that identifies a type.
Then, anywhere in the function where T appears, it is replaced with whatever
type the function is instantiated.
int i=3;
float d=4.75;
char *s="hello";
printData(i); // T is int
printData(d); // T is float
printData(s); // T is string
OVERLOADED FUNCTION TEMPLATE
 Like ordinary functions, function templates can be overloaded.
 We can have different function definitions with the same function name so that when
that name is used in a function call, a C++ compiler must decide which one of the
various functions to call.
 The rules for this decision may become rather complicated, even without templates.
 Generic functions perform the same operation for all the versions of a function except
the data type differs.
 The overloading resolution is accomplished as follows:
 Call an ordinary function that has an exact match.
 Call a template function could be created with an exact match.
 Try normal overloading resolution to ordinary functions and call the one that matches.
 An error is generated if no match is found. Note that no automatic conversions are
applied to arguments on the template functions.
CLASS TEMPLATE
 Sometimes, you need a class implementation that is same for all classes, only the data
types used are different.
 Normally, you would need to create a different class for each data type OR create
different member variables and functions within a single class.
 Syntax:
template <class type>
class classname
{
type member1;
public:
type fun();
};
CLASS TEMPLATE
 The object of template class is created as follows
class name <data type> object name;
template<class Ttype>
class sample
{
Ttype a,b;
public:
void getdata()
{
cin>>a>>b;
}
void sum();
};
int main()
{
sample <int>s1;
sample <float>s2;
s1.getdata();
s1.sum();
s2.getdata();
s2.sum();
}
 Generic classes are useful when a class contains generalizable
logic.
 For example, the same algorithm that maintains a queue of
integers will also work for a queue of characters. Also, the same
mechanism that maintains a linked list of mailing addresses will
also maintain a linked of auto part information.
 By using a generic class, you can create a class that will
maintain a queue, a linked list, and so on for any type of data.
 The compiler will automatically generate the correct type of
object based upon the type you specify when the object is
created.
 C++ provides a library that is built upon template classes. This
library is usually referred to as the Standard Template Library, or
STL for short.
 It provides generic versions of the most commonly used
algorithms and data structures.
CLASS TEMPLATE INHERITANCE
 The template class can also act as base class.
 There are 3 cases:-
 Derive a template class and add new member to it, the base class must be
of template type.
 Derive a class from non-template class add new template type members
to derive class.
 Derive a class from a template base class and omit the template features
in the derive class.
 This can be done by declaring the type while deriving the class.
 All the template based variables are substituted with basic data type.
SUMMARY
 C++ supports a mechanism known as template to implement the concept of generic
programming.
 Template allows us to generate a family of classes or a family of functions to handle different
data types.
 Template classes and functions eliminate code duplication for different types and thus make
the program development easier and more manageable.
 We can use multiple parameters in both the class templates and function templates.
 A specific class created from a class template is called a template class and the process of
creating a template class is known as instantiation.
 Like other functions, template functions can be overloaded.
 Member function of a class template must be defined as function templates using the
parameters of the class template.
 We may also use non type parameters such basic or derived data types as arguments
templates.
CONTAINERSHIP
 We can create an object of one class into another and that
object will be a member of the class. This type of relationship
between classes is known as containership or has_a relationship
as one class contain the object of another class.
 And the class which contains the object and members of
another class in this kind of relationship is called a container class.
 The object that is part of another object is called contained
object, whereas object that contains another object as its part or
attribute is called container object.
CONTAINERSHIP
 Syntax:
Class a //contained class
{
..
..
}
Class b //container class
{
..
a A;

}

More Related Content

Similar to 6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS.pptx (20)

Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
nirajmandaliya
Functions in C++
Functions in C++Functions in C++
Functions in C++
Pranali Chaudhari
Polymorphism
PolymorphismPolymorphism
Polymorphism
Prof .Pragati Khade
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
Kaushik Raghupathi
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
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
Jagan Mohan Bishoyi
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming language
HariTharshiniBscIT1
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
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
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
JITTAYASHWANTHREDDY
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Mufaddal Nullwala
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
Virtual function
Virtual functionVirtual function
Virtual function
sdrhr
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
syedabbas594247
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
nirajmandaliya
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
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
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
Jagan Mohan Bishoyi
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming language
HariTharshiniBscIT1
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
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
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
Virtual function
Virtual functionVirtual function
Virtual function
sdrhr
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
syedabbas594247

Recently uploaded (20)

Turbocor Product and Technology Review.pdf
Turbocor Product and Technology Review.pdfTurbocor Product and Technology Review.pdf
Turbocor Product and Technology Review.pdf
Totok Sulistiyanto
TM-ASP-101-RF_Air Press manual crimping machine.pdf
TM-ASP-101-RF_Air Press manual crimping machine.pdfTM-ASP-101-RF_Air Press manual crimping machine.pdf
TM-ASP-101-RF_Air Press manual crimping machine.pdf
ChungLe60
GM Meeting 070225 TO 130225 for 2024.pptx
GM Meeting 070225 TO 130225 for 2024.pptxGM Meeting 070225 TO 130225 for 2024.pptx
GM Meeting 070225 TO 130225 for 2024.pptx
crdslalcomumbai
US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...
US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...
US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...
Thane Heins NOBEL PRIZE WINNING ENERGY RESEARCHER
Soil Properties and Methods of Determination
Soil Properties and  Methods of DeterminationSoil Properties and  Methods of Determination
Soil Properties and Methods of Determination
Rajani Vyawahare
Indian Soil Classification System in Geotechnical Engineering
Indian Soil Classification System in Geotechnical EngineeringIndian Soil Classification System in Geotechnical Engineering
Indian Soil Classification System in Geotechnical Engineering
Rajani Vyawahare
Multi objective genetic approach with Ranking
Multi objective genetic approach with RankingMulti objective genetic approach with Ranking
Multi objective genetic approach with Ranking
namisha18
CONTRACTOR ALL RISK INSURANCESAR (1).ppt
CONTRACTOR ALL RISK INSURANCESAR (1).pptCONTRACTOR ALL RISK INSURANCESAR (1).ppt
CONTRACTOR ALL RISK INSURANCESAR (1).ppt
suaktonny
Piping-and-pipeline-calculations-manual.pdf
Piping-and-pipeline-calculations-manual.pdfPiping-and-pipeline-calculations-manual.pdf
Piping-and-pipeline-calculations-manual.pdf
OMI0721
decarbonization steel industry rev1.pptx
decarbonization steel industry rev1.pptxdecarbonization steel industry rev1.pptx
decarbonization steel industry rev1.pptx
gonzalezolabarriaped
Cloud Computing concepts and technologies
Cloud Computing concepts and technologiesCloud Computing concepts and technologies
Cloud Computing concepts and technologies
ssuser4c9444
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...
ASHISHDESAI85
Lecture -3 Cold water supply system.pptx
Lecture -3 Cold water supply system.pptxLecture -3 Cold water supply system.pptx
Lecture -3 Cold water supply system.pptx
rabiaatif2
Power Point Presentation for Electrical Engineering 3-phase.ppt
Power Point Presentation for Electrical Engineering 3-phase.pptPower Point Presentation for Electrical Engineering 3-phase.ppt
Power Point Presentation for Electrical Engineering 3-phase.ppt
Aniket_1415
Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...
dhanashree78
GREEN BULIDING PPT FOR THE REFRENACE.PPT
GREEN BULIDING PPT FOR THE REFRENACE.PPTGREEN BULIDING PPT FOR THE REFRENACE.PPT
GREEN BULIDING PPT FOR THE REFRENACE.PPT
kamalkeerthan61
only history of java.pptx real bihind the name java
only history of java.pptx real bihind the name javaonly history of java.pptx real bihind the name java
only history of java.pptx real bihind the name java
mushtaqsaliq9
GROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptx
GROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptxGROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptx
GROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptx
meneememoo
Name.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
Name.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVName.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
Name.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
MerijimArsedelPalmad1
04 MAINTENANCE OF CONCRETE PAVEMENTS.ppt
04  MAINTENANCE OF CONCRETE PAVEMENTS.ppt04  MAINTENANCE OF CONCRETE PAVEMENTS.ppt
04 MAINTENANCE OF CONCRETE PAVEMENTS.ppt
sreenath seenu
Turbocor Product and Technology Review.pdf
Turbocor Product and Technology Review.pdfTurbocor Product and Technology Review.pdf
Turbocor Product and Technology Review.pdf
Totok Sulistiyanto
TM-ASP-101-RF_Air Press manual crimping machine.pdf
TM-ASP-101-RF_Air Press manual crimping machine.pdfTM-ASP-101-RF_Air Press manual crimping machine.pdf
TM-ASP-101-RF_Air Press manual crimping machine.pdf
ChungLe60
GM Meeting 070225 TO 130225 for 2024.pptx
GM Meeting 070225 TO 130225 for 2024.pptxGM Meeting 070225 TO 130225 for 2024.pptx
GM Meeting 070225 TO 130225 for 2024.pptx
crdslalcomumbai
Soil Properties and Methods of Determination
Soil Properties and  Methods of DeterminationSoil Properties and  Methods of Determination
Soil Properties and Methods of Determination
Rajani Vyawahare
Indian Soil Classification System in Geotechnical Engineering
Indian Soil Classification System in Geotechnical EngineeringIndian Soil Classification System in Geotechnical Engineering
Indian Soil Classification System in Geotechnical Engineering
Rajani Vyawahare
Multi objective genetic approach with Ranking
Multi objective genetic approach with RankingMulti objective genetic approach with Ranking
Multi objective genetic approach with Ranking
namisha18
CONTRACTOR ALL RISK INSURANCESAR (1).ppt
CONTRACTOR ALL RISK INSURANCESAR (1).pptCONTRACTOR ALL RISK INSURANCESAR (1).ppt
CONTRACTOR ALL RISK INSURANCESAR (1).ppt
suaktonny
Piping-and-pipeline-calculations-manual.pdf
Piping-and-pipeline-calculations-manual.pdfPiping-and-pipeline-calculations-manual.pdf
Piping-and-pipeline-calculations-manual.pdf
OMI0721
decarbonization steel industry rev1.pptx
decarbonization steel industry rev1.pptxdecarbonization steel industry rev1.pptx
decarbonization steel industry rev1.pptx
gonzalezolabarriaped
Cloud Computing concepts and technologies
Cloud Computing concepts and technologiesCloud Computing concepts and technologies
Cloud Computing concepts and technologies
ssuser4c9444
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...
ASHISHDESAI85
Lecture -3 Cold water supply system.pptx
Lecture -3 Cold water supply system.pptxLecture -3 Cold water supply system.pptx
Lecture -3 Cold water supply system.pptx
rabiaatif2
Power Point Presentation for Electrical Engineering 3-phase.ppt
Power Point Presentation for Electrical Engineering 3-phase.pptPower Point Presentation for Electrical Engineering 3-phase.ppt
Power Point Presentation for Electrical Engineering 3-phase.ppt
Aniket_1415
Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...
dhanashree78
GREEN BULIDING PPT FOR THE REFRENACE.PPT
GREEN BULIDING PPT FOR THE REFRENACE.PPTGREEN BULIDING PPT FOR THE REFRENACE.PPT
GREEN BULIDING PPT FOR THE REFRENACE.PPT
kamalkeerthan61
only history of java.pptx real bihind the name java
only history of java.pptx real bihind the name javaonly history of java.pptx real bihind the name java
only history of java.pptx real bihind the name java
mushtaqsaliq9
GROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptx
GROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptxGROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptx
GROUP-3-GRID-CODE-AND-DISTRIBUTION-CODE.pptx
meneememoo
Name.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
Name.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVName.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
Name.docxVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
MerijimArsedelPalmad1
04 MAINTENANCE OF CONCRETE PAVEMENTS.ppt
04  MAINTENANCE OF CONCRETE PAVEMENTS.ppt04  MAINTENANCE OF CONCRETE PAVEMENTS.ppt
04 MAINTENANCE OF CONCRETE PAVEMENTS.ppt
sreenath seenu

6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS.pptx

  • 2. POINTERS Pointer is a derived data type that refers to the address of another variable. A pointer variable tells that where to get the data instead of telling the actual data. The declaration of the pointer is based on the data type of the variable it points to. data-type *pointer-variable At any point of time a pointer variable can point to only one data type. int *ptr; Here ptr contains the memory location of any integer variable. e.g. int *ptr , a; //Declaration ptr=&a; //Initialization
  • 3. int a = 25; int *p; p = &a; cout<<"&a:"<<&a; cout<<"p:"<<p; cout<<"&p:"<<&p; cout<<"*p:"<<*p; cout<<"*(&a):"<<*(&a); (*p)++; cout<<"*p:"<<*p; cout<<"a:"<<a;a 25 1000 p a 1000 2000
  • 4. int a = 25; int *p,**s; p = &a; s = &p; cout<<"n*p:"<<*p; cout<<"n*s:"<<*s; cout<<"n**s:"<<**s; cout<<"n*(*(&p)):"<<*(*(&p)); cout<<"n***(&s):"<<***(&s);
  • 5. POINTERS WITH ARRAYS Pointers are associated with arrays as: Pointers are useful to allocate arrays dynamically Efficient tools to access the elements of an array. We can declare pointers to arrays as ; int *ptr; ptr = number[0]; OR ptr = number; An array of Pointer is an array of addresses i.e all the elements of the Pointer array points to an item of the data array. An array of Pointer is declared as int *abc[10]; It is an array of ten pointers ie. Addresses all of them points to an integer. Before initializing they point to some unknown values in the memory space.
  • 6. int main () { int arr[5] = {10,20,30,40,50}; int *ptr; ptr = &arr[0]; for ( int i = 0; i < 5; i++ ) { cout <<"*(ptr+" << i <<"):"; cout <<*(ptr + i) << endl; } return 0; }
  • 7. POINTERS TO OBJECTS Just like pointers to normal variables and functions, we can have pointers to class members (variables and methods). class ABC { public: int a=50; }; int main() { ABC ob1; ABC *ptr; ptr = &ob1; cout << ob1.a; cout << ptr->a; // Accessing members of class with pointer }
  • 8. class demo{ int i; public: demo(int x){ i=x; } int getdata(){ return i;} }; int main() { demo d[3]={55,66,77}; demo *ptr=d; //similar to *ptr=&d[0] for(int i=0;i<3;i++) { cout<<ptr->getdata()<<endl; ptr++; } }
  • 9. Practice Program Create a class student having private members marks, name and public members rollno, getdata(), printdata(). Demonstrate concept of pointer to class members for array of 3 objects.
  • 10. THIS POINTER this pointer represent an object that invoke or call a member function. It will point to the object for which member function is called. It is automatically passed to a member function when it is called. It is also called as implicit argument to all member function. Friend functions can not be accessed using this pointer, because friends are not members of a class. Only member functions have a this pointer. A static member function does not have this pointer.
  • 11. THIS POINTER Following are the situations where this pointer is used. When local variables name is same as members name To return reference to the calling object
  • 12. class sample { int a,b; public: void input(int a,int b){ this->a = a + b; this->b = a - b; } void output(){ cout<<"a = "<<a; cout<<"b = "<<b; } }; int main() { sample ob1; int a=5,b=8; ob1.input(a,b); ob1.output(); }
  • 13. class Test { int x; int y; public: Test& setX(int a) { x = a; return *this; } //Reference to the calling object can be returned Test& setY(int b) { y = b; return *this; } void print() { cout << "x = " << x ; cout << " y = " << y; } }; int main() { Test obj1; obj1.setX(10).setY(20); // chain function calls obj1.print(); }
  • 14. POINTERS TO DERIVED CLASS We can use pointers not only to the base objects but also to the objects of derived classes. Pointers to the base classes are type-compatible to the objects of the derived classes. Hence, A single pointer variable of base type can be made to point to objects belonging to base as well as derived classes. E.g. Here B is a base class, D is Derived class. B *cptr; B b; D d; cptr=&b; we can also make the cptr to point to object d also. cptr=&d; As d is an object derived from the class B
  • 15. POINTERS TO DERIVED CLASS We can access those members of derived class which are inherited from base class by base class pointer. But we cannot access original member of derived class which are not inherited from base class using base class pointer. We can access original member of derived class using pointer of derived class.
  • 16. VIRTUAL FUNCTIONS A virtual function is a member function that is declared within a base class and redefined by a derived class. To create a virtual function, precede the function's declaration in the base class with the keyword virtual. When virtual function accessed "normally," it behave just like any other type of class member function. But when it is accessed via a pointer it supports run time polymorphism. Base class and derived class have same function name and base class pointer is assigned address of derived class object then also pointer will execute base class function. After making virtual function, the compiler will determine which function to execute at run time on the basis of assigned address to pointer of base class.
  • 17. RULES FOR VIRTUAL FUNCTIONS The virtual functions must be member of any class. They cannot be static members. They are accessed by using object pointers. A virtual function can be a friend of another class. A virtual function in a base class must be defined, even though it may not be used. We cannot have virtual constructors, but we can have virtual destructors. The derived class pointer cannot point to the object of base class. When a base pointer points to a derived class, then also it is incremented or decremented only relative to its base type. Therefore we should not use this method to move the pointer to the next object. If a virtual function is defined in base class, it need not be necessarily redefined in the derived class. In such cases, call will invoke the base class.
  • 18. PURE VIRTUAL FUNCTIONS A pure virtual function is virtual function that has no definition within the base class. A pure virtual function means do nothing function. We can say empty function. A pure virtual function has no definition relative to the base class. Programmers have to redefine pure virtual function in derived class, because it has no definition in base class. A class containing pure virtual function cannot be used to create any direct objects of its own. This type of class is also called as abstract class.
  • 19. PURE VIRTUAL FUNCTIONS Syntax: virtual void display() = 0; OR virtual void display() {}
  • 20. ABSTRACT CLASS A class that contains at least one pure virtual function is called abstract class. You can not create objects of an abstract class, you can create pointers and references to an abstract class.
  • 21. VIRUTAL DESTRUCTOR Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. Making base class destructor virtual guarantees that the object of derived class is destructed properly, i.e., both base class and derived class destructors are called.
  • 23. INTRODUCTION C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code that behaves the same for any data type. By template we can define generic classes and functions. In simple terms, you can create a single function or a class to work with different data types using templates. It can be considered as a kind of macro. When an object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type.
  • 25. FUNCTION TEMPLATE A function template specifies how an individual function can be constructed. We write a generic function that can be used for different data types. Syntax: template <class T> T functionname(T arg1,T arg2) { function body; }
  • 26. A generic function defines a general set of operations that will be applied to various types of data. A generic function has the type of data that it will operate upon passed to it as a parameter. Using this mechanism, the same general procedure can be applied to a wide range of data. For example the Quicksort algorithm is the same whether it is applied to an array of integers or an array of floats. It is just that the type of data being sorted is different. By creating a generic function, you can define, independent of any data, the nature of the algorithm. Once this is done, the compiler automatically generates the correct code for the type of data that is actually used when you execute the function. In essence, when you create a generic function you are creating a function that can automatically overload itself. A generic function is also called a template function. When the compiler creates a specific version of the function, it is said to have created a generated function. Generic functions may be overloaded.
  • 27. Suppose you write a function printData: void printData(int value){ cout<<"The value is "<<value; } Now if you want to print double values or string values, then you have to overload the function: void printData(float value){ cout<<"The value is "<<value; } void printData(char *value) { cout<<"The value is "<<*value; } To perform same operation with different data type, we have to write same code multiple time.
  • 28. C++ provides templates to reduce this type of duplication of code. template<class T> void printData(T value){ cout<<"The value is "<<value; } We can now use printData for any data type. Here T is a template parameter that identifies a type. Then, anywhere in the function where T appears, it is replaced with whatever type the function is instantiated. int i=3; float d=4.75; char *s="hello"; printData(i); // T is int printData(d); // T is float printData(s); // T is string
  • 29. OVERLOADED FUNCTION TEMPLATE Like ordinary functions, function templates can be overloaded. We can have different function definitions with the same function name so that when that name is used in a function call, a C++ compiler must decide which one of the various functions to call. The rules for this decision may become rather complicated, even without templates. Generic functions perform the same operation for all the versions of a function except the data type differs. The overloading resolution is accomplished as follows: Call an ordinary function that has an exact match. Call a template function could be created with an exact match. Try normal overloading resolution to ordinary functions and call the one that matches. An error is generated if no match is found. Note that no automatic conversions are applied to arguments on the template functions.
  • 30. CLASS TEMPLATE Sometimes, you need a class implementation that is same for all classes, only the data types used are different. Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class. Syntax: template <class type> class classname { type member1; public: type fun(); };
  • 31. CLASS TEMPLATE The object of template class is created as follows class name <data type> object name;
  • 32. template<class Ttype> class sample { Ttype a,b; public: void getdata() { cin>>a>>b; } void sum(); }; int main() { sample <int>s1; sample <float>s2; s1.getdata(); s1.sum(); s2.getdata(); s2.sum(); }
  • 33. Generic classes are useful when a class contains generalizable logic. For example, the same algorithm that maintains a queue of integers will also work for a queue of characters. Also, the same mechanism that maintains a linked list of mailing addresses will also maintain a linked of auto part information. By using a generic class, you can create a class that will maintain a queue, a linked list, and so on for any type of data. The compiler will automatically generate the correct type of object based upon the type you specify when the object is created. C++ provides a library that is built upon template classes. This library is usually referred to as the Standard Template Library, or STL for short. It provides generic versions of the most commonly used algorithms and data structures.
  • 34. CLASS TEMPLATE INHERITANCE The template class can also act as base class. There are 3 cases:- Derive a template class and add new member to it, the base class must be of template type. Derive a class from non-template class add new template type members to derive class. Derive a class from a template base class and omit the template features in the derive class. This can be done by declaring the type while deriving the class. All the template based variables are substituted with basic data type.
  • 35. SUMMARY C++ supports a mechanism known as template to implement the concept of generic programming. Template allows us to generate a family of classes or a family of functions to handle different data types. Template classes and functions eliminate code duplication for different types and thus make the program development easier and more manageable. We can use multiple parameters in both the class templates and function templates. A specific class created from a class template is called a template class and the process of creating a template class is known as instantiation. Like other functions, template functions can be overloaded. Member function of a class template must be defined as function templates using the parameters of the class template. We may also use non type parameters such basic or derived data types as arguments templates.
  • 36. CONTAINERSHIP We can create an object of one class into another and that object will be a member of the class. This type of relationship between classes is known as containership or has_a relationship as one class contain the object of another class. And the class which contains the object and members of another class in this kind of relationship is called a container class. The object that is part of another object is called contained object, whereas object that contains another object as its part or attribute is called container object.
  • 37. CONTAINERSHIP Syntax: Class a //contained class { .. .. } Class b //container class { .. a A; }

Editor's Notes

  • #3: &a: 1000, p: 1000, &p: 2000, *p: 25, *(&a):25, *p: 26, a:26
  • #4: A= 25 at address 1000, p=1000 at address 2000, s=2000 at address 3000 Output: *p: 25, *s: 1000, **s: 25, *(*(&p)):25, ***(&s): 25
  • #6: *(ptr + 0) : 10 *(ptr + 1) : 20 *(ptr + 2) : 30 *(ptr + 3) : 40 *(ptr + 4) : 50
  • #7: When accessing members of a class given a pointer to an object, use the arrow (>) operator instead of the dot operator.
  • #8: When a pointer incremented it points to next element of its type. An integer pointer will point to the next integer. The same is true for pointer to objects.
  • #13: When a reference to a local object is returned, the returned reference can be used to油chain function calls油on a single object.
  • #21: As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor (even if it does nothing)