SlideShare a Scribd company logo
MODULE 2
ARRAYS, POINTERS, REFERENCES,
AND THE DYNAMIC ALLOCATION
OPERATORS
ARRAYS OF OBJECTS
 In C++, it is possible to have arrays of objects.
 Arrays of variables that are of type class. Such variables are called arrays of objects.
#include<iostream>
using namespace std;
class employee
{
char name[20];
int age;
public:
void getdata();
void putdata();
};
void employee::getdata()
{
cout<<"enter name :";
cin>>name;
cout<<"enter age ";
cin>>age;
}
void employee::putdata()
{
cout<<"name:"<<name <<endl;
cout<<"Age:"<<age<<endl;
}
int main()
{
employee emp[3];//array of object
for( int i=0;i<3;i++)
{
emp[i].getdata();
}
for(int i=0;i<3;i++)
{
emp[i].putdata();
}
return(0);
}
ARRAYS OF OBJECTS
 If a class defines a parameterized constructor, you may initialize each object in an array
by specifying an initialization list.
 the exact form of the initialization list will be decided by the number of parameters
required by the object's constructors.
 objects whose constructors have only one parameter, you can simply specify a list of
initial values, using the normal array-initialization syntax.
 As each element in the array is created, a value from the list is passed to the
constructor’s parameter
 EX: employee emp[2]={employee(“rama”,19),employee(“raju”,25)};
ARRAYS OF OBJECTS: PARAMETERIZED CONSTRUCTOR
#include<iostream>
#include<string>
using namespace std;
class employee
{
string name;
int age;
public:
employee(string NAME,int n);
void putdata();
};
employee::employee(string NAME,int n)
{
name=NAME;
age=n;
}
void employee::putdata()
{
cout<<"name:"<<name<<"tAge:"<<age<<endl;
}
int main()
{
employee emp[2]={employee("rama",20),employee("raju",19)};
for(int i=0;i<2;i++)
{
emp[i].putdata();
}
return(0);
POINTERS TO OBJECTS
 As you can have pointers to other types of variables, you can have pointers to objects.
 Object pointers are very useful whenever creating objects at the run time.
 When accessing members of a class given a pointer to an object, use the arrow (–>)
operator instead of the dot operator.
Syntax:
Class_name *Pointer_variable;
Pointer_variable=&object_name;
Pointer_variable->memberfunction();
Example:
Employee e;
Employee *emp;
Emp=&e
Emp->getdata();
THETHIS POINTER
 C++ uses a unique keyword called "this" to represent an object that invokes a member
function.
 'this' is a pointer that points to the object on which this function is called.
 This unique pointer is called and it passes to the member function
automatically.
 The pointer this acts as an implicit argument to all the member function,
class ABC
{
int a ;
-----
-----
};
• The private variable ‘a’ can be used directly inside a member function, like
a=123;
• We can also use the following statement to do the same job.
this → a = 123
THETHIS POINTER: EXAMPLE
class stud
{
int x;
public:
void set (int a)
{
this → x = a;
}
void show ( )
{
cout << x;
}
};
main ( )
{
stud S1, S2;
S1.set (5) ;
S1.show ( );
}
POINTERS TO DERIVED TYPES(CLASSES)
 Polymorphism is also accomplished using pointers in C++.
 It allows a pointer in a base class to point to either a base class object or to any
derived class object.
 Example if B is a base class and D is a derived class from B , Then a pointer declare as a
pointer to B can also be a pointer to D
class B
{
//Data Members
//Member Functions
};
class D : public B
{
//Data Members
//Member functions
};
int main ( )
{
B *ptr; //pointer to class base
D obj ;
ptr = &obj ; //indirect reference obj to the pointer
//Other Program statements
}
POINTERS TO CLASS MEMBERS
 C++ allows you to generate 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, for
short.
 pointer to a member provides only an offset into an object of the member's class at
which that member can be found.
 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, you must 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.
POINTERS TO CLASS MEMBERS: EXAMPLE
#include <iostream>
using namespace std;
class cl {
public:
cl(int i) { val=i; }
int val;
int double_val()
{
return val+val;
}
};
int main()
{
int cl::*data; // data member pointer
int (cl::*func)(); // function member pointer
cl ob1(1), ob2(2); // create objects
data = &cl::val; // get offset of val
func = &cl::double_val; // get offset of double_val()
cout << "Here are values: ";
cout << ob1.*data << " " << ob2.*data << "n";
cout << "Here they are doubled: ";
cout << (ob1.*func)() << " ";
cout << (ob2.*func)() << "n";
return 0;}
FUNCTION OVERLOADING,
COPY CONSTRUCTORS,
AND DEFAULT ARGUMENTS
FUNCTION OVERLOADING
 Overloading refers to the use of the same thing for different purposes .
C++ also permits overloading functions.
 we can use the same function names to create functions that perform
various tasks. This is known as function polymorphism in Object oriented
programming.
 Using the concepts of function overloading, a family of functions with one
function name but with different argument lists in the functions call.
 The correct function to be invoked is determined by checking the number
and type of the arguments but not the function type.
FUNCTION OVERLOADING
 For example an overloaded add() function handles different types of data as shown
below.
//Declaration
int add(int a, int b); //prototype 1
int add(int a, int b, int c); // prototype 2
double add(double x, double y) // prototype 3
double add(int p,double q); // prototype 4
double add(double p, int q); // prototype 5
//function call
cout<<add(7,10); // uses prototype 1
cout<<add(67,34,23); // uses prototype 2
cout<<add(34.5,23.6); // uses prototype 3
cout<<add(12,34.7); // uses prototype 4
cout<<add(34.7,12); // uses prototype 5
FUNCTION OVERLOADING
 A function call first matches the prototype having the same no and type of arguments
and then calls the appropriate function for execution.
 The function selection invokes the following steps:-
1. The compiler first tries to find an exact match in which the types of actual arguments
are the same and use that function.
2. If an exact match is not found the compiler uses the integral promotions to the actual
arguments such as :
1. char to int
2. float to double to find a match
FUNCTION OVERLOADING
3. When either of them fails, the compiler tries to use the built-in conversions(implicit
assignment conversions) to the actual arguments and then uses the function whose
match is unique. if the conversion is possible to have multiple matches, then the
compiler will generate an error message. suppose we use the following two functions
 long square(long n)
 double square(double x)
 A function call such as :- square(5)
 Will cause an error because int argument can be converted to either long or
double. Thereby creating an ambiguous situation as to which version of square(
)should be used.
FUNCTION OVERLOADING: EXAMPLE
#include <iostream>
using namespace std;
int volume(int);
double volume(double, int);
long volume(long,int,int);
int main()
{
cout<<volume(10)<<"n";
cout<<volume(2.5,8)<<"n";
cout<<volume(100L,75,15)<<"n
";
return 0;
}
int volume(int s) //cube
{
return (s*s*s);
}
double volume(double r, int h) // cylinder
{
return (3.14519*r*r*h);
}
long volume(long l, int b, int h) // rectangular box
{
return (l*b*h);
}
OVERLOADING CONSTRUCTORS
 Constructors can be overloaded; in fact, overloaded constructors are very common.
 There are three main reasons why to overload a constructor:
 to gain flexibility,
 to allow both initialized and uninitialized objects to be created,
 and to define copy constructors
OVERLOADING CONSTRUCTORS:EXAMPLE
#include<iostream>
using namespace std;
class A
{
int i,j;
public: A();
A(int,int);
A(A &);
};
A::A()
{
cout<<"default constructorn";
}
A::A(int x,int y)
{
cout<<"parameterized
constructorn";
i=x;
j=y;
}
A::A(A &a)
{
cout<<"copy constructorn";
i=a.i;
j=a.j;
}
int main()
{
A c;
A b(20,20);
A a(b);
OVERLOADING A CONSTRUCTOR TO GAIN FLEXIBILITY
 Many times you will create a class for which there are two or more possible ways to
construct an object.
 In these cases, you will want to provide an overloaded constructor for each way.
 This is a self-enforcing rule because if you attempt to create an object for which there
is no matching constructor, a compile-time error results.
 By providing a constructor for each way that a user of your class may plausibly want to
construct an object, you increase the flexibility of your class.
 The user is free to choose the best way to construct an object given the specific
circumstance
#include <iostream>
#include <cstdio>
using namespace std;
class date
{
int day, month, year;
public:
date(char *d);
date(int m, int d, int y);
void show_date();
};
// Initialize using string.
date::date(char *d)
{
sscanf(d, "%d%*c%d%*c%d", &month, &day, &year);
}
// Initialize using integers.
date::date(int m, int d, int y)
{
day = d;
month = m;
year = y;
}
void date::show_date()
{
cout << month << "/" << day;
cout << "/" << year << "n";
}
int main()
{
date ob1(12, 4, 2003), ob2("10/22/2003");
ob1.show_date();
ob2.show_date();
return 0;
}
ALLOWING BOTH INITIALIZED AND UNINITIALIZED OBJECTS
 Another common reason constructors are overloaded is to allow both initialized and
uninitialized objects (or, more precisely, default initialized objects) to be created.
 This is especially important if you want to be able to create dynamic arrays of objects
of some class, since it is not possible to initialize a dynamically allocated array.
 To allow uninitialized arrays of objects along with initialized objects, you must include a
constructor that supports initialization and one that does not.
COPY CONSTRUCTORS
 One of the more important forms of an overloaded constructor is the copy
constructor.
 Defining a copy constructor can help you prevent problems that might occur when one
object is used to initialize another
classname (const classname &o)
{
// body of constructor
}
in all cases, the first parameter must be a reference to
the object doing the initializing
COPY CONSTRUCTORS
 It is important to understand that C++ defines two distinct types of situations in which
the value of one object is given to another.
 The first is assignment.
 The second is initialization, which can occur any of three ways:
 When one object explicitly initializes another, such as in a declaration
 When a copy of an object is made to be passed to a function
 When a temporary object is generated (most commonly, as a return value)
 Example: myclass x = y; // y explicitly initializing x
func(y); // y passed as a parameter
y = func(); // y receiving a temporary, return object
DEFAULT FUNCTION ARGUMENT
 C++ allows us to call a function without specifying all its arguments.
 In such cases, the function assigns a default value to the parameter that does not have matching
arguments in the function call.
 Default values are specified when the function is declared.
 The compiler looks at the prototype to see how many arguments a function uses and alerts
the program for possible default values.
 Example: float amount (float principle, int period , float rate=0.15);
 The default value is specified in a manner syntactically similar to a variable initialization.The
above prototype declares a default value of 0.15 to the argument rate.
 A subsequent function call like
 value=amount(5000,7); //one argument missing
DEFAULT FUNCTION ARGUMENT
 One important note is that only the trailing arguments can have default values. That is,
we must add default from right to left.
 We cannot provide a default to a particular argument in the middle of an argument list.
 Advantages of providing the default arguments are:
1. We can use default arguments to add new parameters to the existing functions.
2. Default arguments can be used to combine similar functions into one.
int mul(int i, int j=5, int k=10); // it is legal
int mul(int i=5,int j); // this is illegal
int mul(int i=0, int j, int k=10); // this is illegal
int mul(int i=2,int j=6; int k=90); // it is legal
DEFAULT FUNCTION ARGUMENT: EXAMPLE
#include <iostream>
using namespace std;
int sum(int x, int y, int z = 0, int w = 0)
{
return (x + y + z + w);
}
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
FUNCTION OVERLOADING AND AMBIGUITY
 You can create a situation in which the compiler is unable to choose between two (or
more) overloaded functions. When this happens, the situation is said to be ambiguous.
 Ambiguous statements are errors, and programs containing ambiguity will not compile.
 By far the main cause of ambiguity involves C++'s automatic type conversions.
 C++ automatically attempts to convert the arguments used to call a function into the
type of arguments expected by the function.
 C++ automatically converts the character c into its double equivalent
int myfunc(double d);
// ...
cout << myfunc('c'); // not an error, conversion applied
FUNCTION OVERLOADING AND AMBIGUITY
 In C++, very few type conversions of this sort are actually disallowed.
 Although automatic type conversions are convenient, they are also a prime cause of
ambiguity.
#include <iostream>
using namespace std;
float myfunc(float i);
double myfunc(double i);
int main()
{
cout << myfunc(10.1) <<endl; // unambiguous, calls
cout << myfunc(10); // ambiguous
return 0;
}
float myfunc(float i)
{
return i;
}
double myfunc(double i)
{
return -i;
}
[Error] call of overloaded 'myfunc(int)' is ambiguous
FUNCTION OVERLOADING AND AMBIGUITY
 In the unambiguous line, myfunc(double) is called because unless explicitly specified as
float, all floating-point constants in C++ are automatically of type double.
 However, when myfunc( ) is called by using the integer 10, ambiguity is introduced
because the compiler has no way of knowing whether it should be converted to a float
or to a double.
 Error it is not the overloading of myfunc( ) relative to double and float that causes the
ambiguity.
 Rather, it is the specific call to myfunc( ) using an indeterminate type of argument that
causes the confusion
FUNCTION OVERLOADING AND AMBIGUITY
 ambiguity caused by C++'s automatic type conversions
#include <iostream>
using namespace std;
char myfunc(unsigned char ch);
char myfunc(char ch);
int main()
{
cout << myfunc('c'); // this calls myfunc(char)
cout << myfunc(88) << " "; // ambiguous
return 0;
}
char myfunc(unsigned char ch)
{
return ch-1;
}
char myfunc(char ch)
{
return ch+1;
}
[Error] call of overloaded 'myfunc(int)' is
ambiguous
FUNCTION OVERLOADING AND AMBIGUITY
 Another way can cause ambiguity is by using default arguments in overloaded functions.
#include <iostream>
using namespace std;
int myfunc(int i);
int myfunc(int i, int j=1);
int main()
{
cout << myfunc(4, 5) << " "; // unambiguous
cout << myfunc(10); // ambiguous
return 0;
}
int myfunc(int i)
{
return i;
}
int myfunc(int i, int j)
{
return i*j;
}
Error:[Error] call of overloaded
'myfunc(int)' is ambiguous
PROGRAMMING EXERCISE
1. Write a program to print the area of a rectangle by creating a class named 'Area'
having one function. Length and breadth of the rectangle are entered through
keyboard using Parameterized constructor.
2. Create a class “Mobile” with attributes: brand, price, color, width, height. Use
constructor to set default values of these attributes.Write function to display details
of all attributes.
3. Create a class “Mobile” with attributes: brand, price, color. Enter detail of five different
mobile. (Using Array of object).Display total number of mobile having price greater
than 5000Display Brand, Price and color for all mobiles for price range 1000 to 10000
PROGRAMMING EXERCISE
1. Create a class “Student” having following data members:
 studid, name, marks (of 5 subject), percentage.
 Use getdata and show functions to input and display student data.
 Create private function to calculate percentage.
 Display detail of student who secured highest percentage.
 Create N number of student using array of object.
2. C++ program to create a class for Employee to get and display following Employee
information:
 Empcode,Emp name, Basicsalary
 Count the created objects using static member

More Related Content

PPTX
21CSC101T best ppt ever OODP UNIT-2.pptx
PPT
Object Oriented Technologies
PPTX
Chapter 2 OOP using C++ (Introduction).pptx
PPT
3d7b7 session4 c++
PPTX
2CPP13 - Operator Overloading
PPTX
Chp 3 C++ for newbies, learn fast and earn fast
PDF
Unit 2 Methods and Polymorphism-Object oriented programming
PDF
Ch-4-Operator Overloading.pdf
21CSC101T best ppt ever OODP UNIT-2.pptx
Object Oriented Technologies
Chapter 2 OOP using C++ (Introduction).pptx
3d7b7 session4 c++
2CPP13 - Operator Overloading
Chp 3 C++ for newbies, learn fast and earn fast
Unit 2 Methods and Polymorphism-Object oriented programming
Ch-4-Operator Overloading.pdf

Similar to 22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf (20)

PPTX
Object Oriented Design and Programming Unit-02
DOCX
Bc0037
PPT
Mca 2nd sem u-2 classes & objects
PDF
Unit3_OOP-converted.pdf
PPT
Bca 2nd sem u-2 classes & objects
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
PPT
443600107-1-Introduction-to-C-ppt (1).ppt
PPT
443600107-1-Introduction-to education -C-ppt
PPTX
11.C++Polymorphism [Autosaved].pptx
PDF
Polymorphism and Type Conversion.pdf pot
PPTX
pointer, virtual function and polymorphism
PPTX
pointers,virtual functions and polymorphism
PPTX
OOP-Lecture-05 (Constructor_Destructor).pptx
PDF
A COMPLETE FILE FOR C++
PDF
2nd puc computer science chapter 8 function overloading
PPTX
Unit ii
PPTX
Pointers, virtual function and polymorphism
PPT
C++ - Constructors,Destructors, Operator overloading and Type conversion
Object Oriented Design and Programming Unit-02
Bc0037
Mca 2nd sem u-2 classes & objects
Unit3_OOP-converted.pdf
Bca 2nd sem u-2 classes & objects
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
443600107-1-Introduction-to-C-ppt (1).ppt
443600107-1-Introduction-to education -C-ppt
11.C++Polymorphism [Autosaved].pptx
Polymorphism and Type Conversion.pdf pot
pointer, virtual function and polymorphism
pointers,virtual functions and polymorphism
OOP-Lecture-05 (Constructor_Destructor).pptx
A COMPLETE FILE FOR C++
2nd puc computer science chapter 8 function overloading
Unit ii
Pointers, virtual function and polymorphism
C++ - Constructors,Destructors, Operator overloading and Type conversion
Ad

Recently uploaded (20)

PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
Digital Logic Computer Design lecture notes
PDF
composite construction of structures.pdf
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Well-logging-methods_new................
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPT
Mechanical Engineering MATERIALS Selection
PDF
PPT on Performance Review to get promotions
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Construction Project Organization Group 2.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Internet of Things (IOT) - A guide to understanding
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Digital Logic Computer Design lecture notes
composite construction of structures.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Lecture Notes Electrical Wiring System Components
CH1 Production IntroductoryConcepts.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Model Code of Practice - Construction Work - 21102022 .pdf
UNIT 4 Total Quality Management .pptx
Well-logging-methods_new................
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Mechanical Engineering MATERIALS Selection
PPT on Performance Review to get promotions
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
R24 SURVEYING LAB MANUAL for civil enggi
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Construction Project Organization Group 2.pptx
Foundation to blockchain - A guide to Blockchain Tech
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Ad

22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf

  • 1. MODULE 2 ARRAYS, POINTERS, REFERENCES, AND THE DYNAMIC ALLOCATION OPERATORS
  • 2. ARRAYS OF OBJECTS  In C++, it is possible to have arrays of objects.  Arrays of variables that are of type class. Such variables are called arrays of objects. #include<iostream> using namespace std; class employee { char name[20]; int age; public: void getdata(); void putdata(); }; void employee::getdata() { cout<<"enter name :"; cin>>name; cout<<"enter age "; cin>>age; } void employee::putdata() { cout<<"name:"<<name <<endl; cout<<"Age:"<<age<<endl; } int main() { employee emp[3];//array of object for( int i=0;i<3;i++) { emp[i].getdata(); } for(int i=0;i<3;i++) { emp[i].putdata(); } return(0); }
  • 3. ARRAYS OF OBJECTS  If a class defines a parameterized constructor, you may initialize each object in an array by specifying an initialization list.  the exact form of the initialization list will be decided by the number of parameters required by the object's constructors.  objects whose constructors have only one parameter, you can simply specify a list of initial values, using the normal array-initialization syntax.  As each element in the array is created, a value from the list is passed to the constructor’s parameter  EX: employee emp[2]={employee(“rama”,19),employee(“raju”,25)};
  • 4. ARRAYS OF OBJECTS: PARAMETERIZED CONSTRUCTOR #include<iostream> #include<string> using namespace std; class employee { string name; int age; public: employee(string NAME,int n); void putdata(); }; employee::employee(string NAME,int n) { name=NAME; age=n; } void employee::putdata() { cout<<"name:"<<name<<"tAge:"<<age<<endl; } int main() { employee emp[2]={employee("rama",20),employee("raju",19)}; for(int i=0;i<2;i++) { emp[i].putdata(); } return(0);
  • 5. POINTERS TO OBJECTS  As you can have pointers to other types of variables, you can have pointers to objects.  Object pointers are very useful whenever creating objects at the run time.  When accessing members of a class given a pointer to an object, use the arrow (–>) operator instead of the dot operator. Syntax: Class_name *Pointer_variable; Pointer_variable=&object_name; Pointer_variable->memberfunction(); Example: Employee e; Employee *emp; Emp=&e Emp->getdata();
  • 6. THETHIS POINTER  C++ uses a unique keyword called "this" to represent an object that invokes a member function.  'this' is a pointer that points to the object on which this function is called.  This unique pointer is called and it passes to the member function automatically.  The pointer this acts as an implicit argument to all the member function, class ABC { int a ; ----- ----- }; • The private variable ‘a’ can be used directly inside a member function, like a=123; • We can also use the following statement to do the same job. this → a = 123
  • 7. THETHIS POINTER: EXAMPLE class stud { int x; public: void set (int a) { this → x = a; } void show ( ) { cout << x; } }; main ( ) { stud S1, S2; S1.set (5) ; S1.show ( ); }
  • 8. POINTERS TO DERIVED TYPES(CLASSES)  Polymorphism is also accomplished using pointers in C++.  It allows a pointer in a base class to point to either a base class object or to any derived class object.  Example if B is a base class and D is a derived class from B , Then a pointer declare as a pointer to B can also be a pointer to D class B { //Data Members //Member Functions }; class D : public B { //Data Members //Member functions }; int main ( ) { B *ptr; //pointer to class base D obj ; ptr = &obj ; //indirect reference obj to the pointer //Other Program statements }
  • 9. POINTERS TO CLASS MEMBERS  C++ allows you to generate 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, for short.  pointer to a member provides only an offset into an object of the member's class at which that member can be found.  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, you must 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.
  • 10. POINTERS TO CLASS MEMBERS: EXAMPLE #include <iostream> using namespace std; class cl { public: cl(int i) { val=i; } int val; int double_val() { return val+val; } }; int main() { int cl::*data; // data member pointer int (cl::*func)(); // function member pointer cl ob1(1), ob2(2); // create objects data = &cl::val; // get offset of val func = &cl::double_val; // get offset of double_val() cout << "Here are values: "; cout << ob1.*data << " " << ob2.*data << "n"; cout << "Here they are doubled: "; cout << (ob1.*func)() << " "; cout << (ob2.*func)() << "n"; return 0;}
  • 12. FUNCTION OVERLOADING  Overloading refers to the use of the same thing for different purposes . C++ also permits overloading functions.  we can use the same function names to create functions that perform various tasks. This is known as function polymorphism in Object oriented programming.  Using the concepts of function overloading, a family of functions with one function name but with different argument lists in the functions call.  The correct function to be invoked is determined by checking the number and type of the arguments but not the function type.
  • 13. FUNCTION OVERLOADING  For example an overloaded add() function handles different types of data as shown below. //Declaration int add(int a, int b); //prototype 1 int add(int a, int b, int c); // prototype 2 double add(double x, double y) // prototype 3 double add(int p,double q); // prototype 4 double add(double p, int q); // prototype 5 //function call cout<<add(7,10); // uses prototype 1 cout<<add(67,34,23); // uses prototype 2 cout<<add(34.5,23.6); // uses prototype 3 cout<<add(12,34.7); // uses prototype 4 cout<<add(34.7,12); // uses prototype 5
  • 14. FUNCTION OVERLOADING  A function call first matches the prototype having the same no and type of arguments and then calls the appropriate function for execution.  The function selection invokes the following steps:- 1. The compiler first tries to find an exact match in which the types of actual arguments are the same and use that function. 2. If an exact match is not found the compiler uses the integral promotions to the actual arguments such as : 1. char to int 2. float to double to find a match
  • 15. FUNCTION OVERLOADING 3. When either of them fails, the compiler tries to use the built-in conversions(implicit assignment conversions) to the actual arguments and then uses the function whose match is unique. if the conversion is possible to have multiple matches, then the compiler will generate an error message. suppose we use the following two functions  long square(long n)  double square(double x)  A function call such as :- square(5)  Will cause an error because int argument can be converted to either long or double. Thereby creating an ambiguous situation as to which version of square( )should be used.
  • 16. FUNCTION OVERLOADING: EXAMPLE #include <iostream> using namespace std; int volume(int); double volume(double, int); long volume(long,int,int); int main() { cout<<volume(10)<<"n"; cout<<volume(2.5,8)<<"n"; cout<<volume(100L,75,15)<<"n "; return 0; } int volume(int s) //cube { return (s*s*s); } double volume(double r, int h) // cylinder { return (3.14519*r*r*h); } long volume(long l, int b, int h) // rectangular box { return (l*b*h); }
  • 17. OVERLOADING CONSTRUCTORS  Constructors can be overloaded; in fact, overloaded constructors are very common.  There are three main reasons why to overload a constructor:  to gain flexibility,  to allow both initialized and uninitialized objects to be created,  and to define copy constructors
  • 18. OVERLOADING CONSTRUCTORS:EXAMPLE #include<iostream> using namespace std; class A { int i,j; public: A(); A(int,int); A(A &); }; A::A() { cout<<"default constructorn"; } A::A(int x,int y) { cout<<"parameterized constructorn"; i=x; j=y; } A::A(A &a) { cout<<"copy constructorn"; i=a.i; j=a.j; } int main() { A c; A b(20,20); A a(b);
  • 19. OVERLOADING A CONSTRUCTOR TO GAIN FLEXIBILITY  Many times you will create a class for which there are two or more possible ways to construct an object.  In these cases, you will want to provide an overloaded constructor for each way.  This is a self-enforcing rule because if you attempt to create an object for which there is no matching constructor, a compile-time error results.  By providing a constructor for each way that a user of your class may plausibly want to construct an object, you increase the flexibility of your class.  The user is free to choose the best way to construct an object given the specific circumstance
  • 20. #include <iostream> #include <cstdio> using namespace std; class date { int day, month, year; public: date(char *d); date(int m, int d, int y); void show_date(); }; // Initialize using string. date::date(char *d) { sscanf(d, "%d%*c%d%*c%d", &month, &day, &year); } // Initialize using integers. date::date(int m, int d, int y) { day = d; month = m; year = y; } void date::show_date() { cout << month << "/" << day; cout << "/" << year << "n"; } int main() { date ob1(12, 4, 2003), ob2("10/22/2003"); ob1.show_date(); ob2.show_date(); return 0; }
  • 21. ALLOWING BOTH INITIALIZED AND UNINITIALIZED OBJECTS  Another common reason constructors are overloaded is to allow both initialized and uninitialized objects (or, more precisely, default initialized objects) to be created.  This is especially important if you want to be able to create dynamic arrays of objects of some class, since it is not possible to initialize a dynamically allocated array.  To allow uninitialized arrays of objects along with initialized objects, you must include a constructor that supports initialization and one that does not.
  • 22. COPY CONSTRUCTORS  One of the more important forms of an overloaded constructor is the copy constructor.  Defining a copy constructor can help you prevent problems that might occur when one object is used to initialize another classname (const classname &o) { // body of constructor } in all cases, the first parameter must be a reference to the object doing the initializing
  • 23. COPY CONSTRUCTORS  It is important to understand that C++ defines two distinct types of situations in which the value of one object is given to another.  The first is assignment.  The second is initialization, which can occur any of three ways:  When one object explicitly initializes another, such as in a declaration  When a copy of an object is made to be passed to a function  When a temporary object is generated (most commonly, as a return value)  Example: myclass x = y; // y explicitly initializing x func(y); // y passed as a parameter y = func(); // y receiving a temporary, return object
  • 24. DEFAULT FUNCTION ARGUMENT  C++ allows us to call a function without specifying all its arguments.  In such cases, the function assigns a default value to the parameter that does not have matching arguments in the function call.  Default values are specified when the function is declared.  The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values.  Example: float amount (float principle, int period , float rate=0.15);  The default value is specified in a manner syntactically similar to a variable initialization.The above prototype declares a default value of 0.15 to the argument rate.  A subsequent function call like  value=amount(5000,7); //one argument missing
  • 25. DEFAULT FUNCTION ARGUMENT  One important note is that only the trailing arguments can have default values. That is, we must add default from right to left.  We cannot provide a default to a particular argument in the middle of an argument list.  Advantages of providing the default arguments are: 1. We can use default arguments to add new parameters to the existing functions. 2. Default arguments can be used to combine similar functions into one. int mul(int i, int j=5, int k=10); // it is legal int mul(int i=5,int j); // this is illegal int mul(int i=0, int j, int k=10); // this is illegal int mul(int i=2,int j=6; int k=90); // it is legal
  • 26. DEFAULT FUNCTION ARGUMENT: EXAMPLE #include <iostream> using namespace std; int sum(int x, int y, int z = 0, int w = 0) { return (x + y + z + w); } int main() { // Statement 1 cout << sum(10, 15) << endl; // Statement 2 cout << sum(10, 15, 25) << endl; // Statement 3 cout << sum(10, 15, 25, 30) << endl; return 0; }
  • 27. FUNCTION OVERLOADING AND AMBIGUITY  You can create a situation in which the compiler is unable to choose between two (or more) overloaded functions. When this happens, the situation is said to be ambiguous.  Ambiguous statements are errors, and programs containing ambiguity will not compile.  By far the main cause of ambiguity involves C++'s automatic type conversions.  C++ automatically attempts to convert the arguments used to call a function into the type of arguments expected by the function.  C++ automatically converts the character c into its double equivalent int myfunc(double d); // ... cout << myfunc('c'); // not an error, conversion applied
  • 28. FUNCTION OVERLOADING AND AMBIGUITY  In C++, very few type conversions of this sort are actually disallowed.  Although automatic type conversions are convenient, they are also a prime cause of ambiguity. #include <iostream> using namespace std; float myfunc(float i); double myfunc(double i); int main() { cout << myfunc(10.1) <<endl; // unambiguous, calls cout << myfunc(10); // ambiguous return 0; } float myfunc(float i) { return i; } double myfunc(double i) { return -i; } [Error] call of overloaded 'myfunc(int)' is ambiguous
  • 29. FUNCTION OVERLOADING AND AMBIGUITY  In the unambiguous line, myfunc(double) is called because unless explicitly specified as float, all floating-point constants in C++ are automatically of type double.  However, when myfunc( ) is called by using the integer 10, ambiguity is introduced because the compiler has no way of knowing whether it should be converted to a float or to a double.  Error it is not the overloading of myfunc( ) relative to double and float that causes the ambiguity.  Rather, it is the specific call to myfunc( ) using an indeterminate type of argument that causes the confusion
  • 30. FUNCTION OVERLOADING AND AMBIGUITY  ambiguity caused by C++'s automatic type conversions #include <iostream> using namespace std; char myfunc(unsigned char ch); char myfunc(char ch); int main() { cout << myfunc('c'); // this calls myfunc(char) cout << myfunc(88) << " "; // ambiguous return 0; } char myfunc(unsigned char ch) { return ch-1; } char myfunc(char ch) { return ch+1; } [Error] call of overloaded 'myfunc(int)' is ambiguous
  • 31. FUNCTION OVERLOADING AND AMBIGUITY  Another way can cause ambiguity is by using default arguments in overloaded functions. #include <iostream> using namespace std; int myfunc(int i); int myfunc(int i, int j=1); int main() { cout << myfunc(4, 5) << " "; // unambiguous cout << myfunc(10); // ambiguous return 0; } int myfunc(int i) { return i; } int myfunc(int i, int j) { return i*j; } Error:[Error] call of overloaded 'myfunc(int)' is ambiguous
  • 32. PROGRAMMING EXERCISE 1. Write a program to print the area of a rectangle by creating a class named 'Area' having one function. Length and breadth of the rectangle are entered through keyboard using Parameterized constructor. 2. Create a class “Mobile” with attributes: brand, price, color, width, height. Use constructor to set default values of these attributes.Write function to display details of all attributes. 3. Create a class “Mobile” with attributes: brand, price, color. Enter detail of five different mobile. (Using Array of object).Display total number of mobile having price greater than 5000Display Brand, Price and color for all mobiles for price range 1000 to 10000
  • 33. PROGRAMMING EXERCISE 1. Create a class “Student” having following data members:  studid, name, marks (of 5 subject), percentage.  Use getdata and show functions to input and display student data.  Create private function to calculate percentage.  Display detail of student who secured highest percentage.  Create N number of student using array of object. 2. C++ program to create a class for Employee to get and display following Employee information:  Empcode,Emp name, Basicsalary  Count the created objects using static member