0% found this document useful (0 votes)
3 views19 pages

Unit II

The document covers concepts related to arrays, pointers, and references in C++, including arrays of objects, pointers to objects, and the use of the 'this' pointer. It also discusses function overloading and copy constructors, providing examples of how to implement these features in code. Additionally, it explains the initialization of arrays of objects and the use of pointers to class members and member functions.

Uploaded by

ananyaprabhu378
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Unit II

The document covers concepts related to arrays, pointers, and references in C++, including arrays of objects, pointers to objects, and the use of the 'this' pointer. It also discusses function overloading and copy constructors, providing examples of how to implement these features in code. Additionally, it explains the initialization of arrays of objects and the use of pointers to class members and member functions.

Uploaded by

ananyaprabhu378
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arrays, Pointers, References

Module - II
Arrays, Pointers, References, and the Dynamic Allocation Operators: Arrays of
Objects, Pointers to Objects, The this Pointer, Pointers to derived types, Pointers to class
members.
Functions Overloading, Copy Constructors: Functions Overloading, Overloading
Constructor Functions, Copy Constructors, Default Function Arguments, Function
Overloading and Ambiguity.

Array of Objects:
 An array is a collection of elements of the same data type, stored in contiguous memory
locations and accessed using an index.
Example:
int num[3] = {10, 20, 30}; // array of integers
 An array of objects is an array where each element is an object of a class.
 It allows storing and handling multiple objects together using array indexing.
Example:
class Student
{
int id;
public:
void read(int i)
{
id = i;
}
void display()
{
cout << "Student ID: " << id << endl;
}
};
int main()
{
Student s[3]; // array of 3 Student objects
/* Student s[3] creates an array of 3 objects (s[0],
s[1], s[2]). You can access and use each object just like
array elements. */

Dept. of ISE, BMSIT&M 1


Arrays, Pointers, References
for (int i = 0; i < 3; i++)
s[i].read(i + 1);

for (int i = 0; i < 3; i++)


s[i].display();
return 0;
}
OUTPUT:
Student ID: 1
Student ID: 2
Student ID: 3

Initializing Arrays of Objects with Constructors:


 When a class has a parameterized constructor, each object must be initialized.
 If there is no default constructor, explicit initialization is required.
 Initialization occurs when the array is created (before main () runs).
 Short form: {1, 2, 3}  works only for one-parameter constructors.
 Long form: {ClassName(1,2), ClassName(3,4)}  for two or more
parameters.
When Constructor Has One Parameter
 You can use a short form (shorthand initialization)  just like initializing an array of
basic data types.
Example:
class Sample
{
int a;
public:
// only parameterized constructor
Sample(int x) { a = x; }
};
int main()
{
Sample s[3]; // ❌ Error: no default constructor
Samepl s[3] = {2,4,6};

Dept. of ISE, BMSIT&M 2


Arrays, Pointers, References

When Constructor Has Two or More Parameters


 You must use the long form, because automatic conversion works only for constructors
with one parameter.
Example:
#include <iostream>
using namespace std;

class cl {
int h, i;
public:
cl(int j, int k) { h = j; i = k; }
// constructor with two parameters
int get_h() { return h; }
int get_i() { return i; }
};

int main()
{
cl ob[3] = {
cl(1, 2),
cl(3, 4),
cl(5, 6)
};

for(int i = 0; i < 3; i++)


cout << ob[i].get_h() << ", " << ob[i].get_i() << endl;

return 0;
}
Constructor Type Example Initialization Form Works?
One parameter cl(int x) {1, 2, 3} Short form works
Two+ parameters cl(int x, int y) {cl(1,2), cl(3,4)} Must use long form
Default constructor cl() cl ob[3]; Creates default objects

Dept. of ISE, BMSIT&M 3


Arrays, Pointers, References

Pointers to Objects:
 A pointer to an object is a variable that stores the address of an object.
 You can use the pointer to access the members of that object using the arrow (->)
operator.
 A pointer can store the address of an object just like it stores the address of a variable.
To access members:
o Use (.) (dot) with objects.
o Use (->) (arrow) with object pointers.
o The arrow operator (->) is shorthand for (*ptr).member.
Example:
class Sample
{
int a;
public:
void setData(int x)
{
a = x;
}
void showData()
{
cout << "Value of a: " << a << endl;
}
};
int main()
{
Sample obj; // normal object
Sample *ptr; // pointer to object
ptr = &obj; // store address of object in pointer
ptr->setData(10); // use arrow operator to call member
ptr->showData(); // access member using pointer
return 0;
}

Dept. of ISE, BMSIT&M 4


Arrays, Pointers, References

Note:
 Pointer arithmetic depends on the base type of the pointer.
 p++ moves to the next object (not just the next byte).
 The arrow operator (->) is used to access members through a pointer.
 Array names act as pointers to the first element.
 Arrays of objects can be processed efficiently using pointers and loops.
Example:
class cl
{
int i;
public:
cl() { i = 0; }
cl(int j) { i = j; }
int get_i() { return i; }
};

int main()
{
cl ob[3] = {1, 2, 3};
cl *p;
int i;
p = ob; // get start address of array
for (i = 0; i < 3; i++)
{
cout << p->get_i() << "\n";
// access value through pointer
p++;
// move to next object
}
return 0;
}

Dept. of ISE, BMSIT&M 5


Arrays, Pointers, References

The this Pointer:


 When a member function is called, it is automatically passed an implicit pointer called
this, which points to the object that invoked the function.
 this is a pointer automatically available inside all non-static member functions.
 It points to the object that invoked the function.
 You can use this->member to access the calling object’s data members explicitly.
Common uses:
 Resolving naming conflicts
 Returning the current object (for function chaining)
 In operator overloading
Example:
class Sample
{
int x;
public:
void setX(int x)
{
this->x = x; // 'this' points to the current object

}
void showX()
{
cout << "x = " << x << endl;
}
};
int main()
{
Sample obj;
[Link](25);
[Link]();
return 0;
}

Dept. of ISE, BMSIT&M 6


Arrays, Pointers, References

Pointers to Class Members:


 A pointer to a class member (also called pointer-to-member) is a special pointer that
points to a class’s member, not to any specific object.
 It represents the offset of that member inside the class, not a true memory address.
 You can use it with any object of that class to access its members indirectly.
 Cannot directly use . or -> with pointer-to-member.
 Requires .* or ->* along with an object or pointer to object.
Pointer to data member:
Syntax:
datatype ClassName::*pointer_name;
Example:
class Student
{
public:
int roll;
int marks;
};

int main()
{
Student s1; // Create object
[Link] = 101;
[Link] = 95;
// Declare a pointer to data member of class Student
int Student::*ptr;
// Make the pointer point to 'marks' member
ptr = &Student::marks;
// Access 'marks' using object and pointer to member
cout << "Marks (using object): " << s1.*ptr << endl;
// Access 'marks' using pointer to object
Student *p = &s1;
cout << "Marks (using pointer to object): " << p->*ptr
<< endl;

return 0;
}

Dept. of ISE, BMSIT&M 7


Arrays, Pointers, References

Pointer to member function:


Syntax:
return_type (ClassName::*pointer_name)(parameter_list);
Example:
class Student
{
public:
void display()
{
cout << "Hello, I am a student!" << endl;
}

int getMarks(int internal, int external)


{
return internal + external;
}
};

int main()
{
Student s; // Create an object
// Pointer to member function (no parameters, returns void)
void (Student::*funcPtr)() = &Student::display;
(s.*funcPtr)(); // Call using object
Student *p = &s; // Pointer to object
(p->*funcPtr)(); // Call using pointer to object
// Pointer to member function that takes 2 int parameters and returns int

int (Student::*markPtr)(int, int) = &Student::getMarks;


// Call using object
cout << "Total Marks (using object): " <<
(s.*markPtr)(40, 50) << endl;

Dept. of ISE, BMSIT&M 8


Arrays, Pointers, References

// Call using pointer to object


cout << "Total Marks (using pointer): " <<
(p->*markPtr)(35, 45) << endl;
return 0;
}
Accessing through object or Pointer:
Access Type Operator Example
Using object .* obj.*data, (obj.*func)()
Using pointer to object ->* ptr->*data, (ptr->*func)()

When to use
 When you want to access or manipulate class members dynamically (for example,
depending on user choice).
 Used in callback mechanisms, reflection-like features, or generic programming.

Dept. of ISE, BMSIT&M 9


Arrays, Pointers, References

Function Overloading (Compile-Time Polymorphism):


 Function overloading is the process of using the same name for two or more functions
but they have different numbers or types of parameters.
 Function overloading is resolved at compile time  also called compile-time
polymorphism.
 Overloading improves readability and usability of functions.
 Always make sure that parameter types or counts are different.
Rules for Function Overloading:
 Same name: All overloaded functions must have the same name.
 Different parameters: Functions must have different number or types of parameters.
 Return type alone won’t work: Overloading cannot depend only on return type.
 Parameter order matters: Changing the order of parameters with different types is
allowed.
 Pointers and arrays are same: int *p and int p[] are treated the same, so
overloading with just this difference is not allowed.
 Decided at compile-time: The compiler chooses which function to call based on
arguments when compiling.
Syntax:
return_type function_name(parameter_list);
Example:
int myfunc(int i); // function with one int parameter
double myfunc(double i); // function with one double parameter
int myfunc(int i, int j); // function with two int parameters

Dept. of ISE, BMSIT&M 10


Arrays, Pointers, References
class Calculator
{
public:
int add(int a, int b) // 1. Different number of parameters
{
return a + b;
}

int add(int a, int b, int c)


{
return a + b + c;
}

double add(double a, double b) // 2. Different types of parameters


{
return a + b;
}

double add(int a, double b) // 3. Different order of parameters


{
return a + b;
}
double add(double a, int b)
{
return a + b;
}
};

int main()
{
Calculator calc;
cout << [Link](2, 3) << endl; // calls int add(int, int)
cout << [Link](1, 2, 3) << endl; // calls int add(int, int, int)
cout << [Link](2.5, 3.5) << endl;// calls double add(double, double)
cout << [Link](5, 2.5) << endl; // calls double add(int, double)
cout << [Link](1.5, 4) << endl; // calls double add(double, int)
return 0;
}

Dept. of ISE, BMSIT&M 11


Arrays, Pointers, References

Overloading Constructor Functions:


 Constructor overloading is the process of defining multiple constructors in a class with
the same name but different parameter lists.
 This allows objects to be created in different ways depending on the available data.
 Flexibility in creating objects.
 Allow both initialized and uninitialized objects.
 Support copy constructors (special case).
Overloading Constructors for Flexibility
 Sometimes a class may need multiple ways to create an object.
 Overloaded constructors allow the user to choose the most convenient way to
initialize an object.
Example:
#include <iostream>
#include <cstdio>
using namespace std;
class Date
{
int day, month, year;
public:
Date(char *d); // initialize using string
Date(int m, int d, int y); // initialize using integers
void show_date();
};

Date::Date(char *d) // Initialize using string


{
sscanf(d, "%d%*c%d%*c%d", &month, &day, &year);
}
Date::Date(int m, int d, int y) // Initialize using integers
{
month = m;
day = d;
year = y;
}

Dept. of ISE, BMSIT&M 12


Arrays, Pointers, References
void Date::show_date()
{
cout << month << "/" << day << "/" << year << "\n";
}

int main()
{
Date ob1(12, 4, 2001); // integer constructor
Date ob2("10/22/2001"); // string constructor

ob1.show_date();
ob2.show_date();

return 0;
}

Overloading Constructors for Initialized & Uninitialized Objects


 Default constructor (no parameters) allows creation of uninitialized objects or
dynamic arrays.
 Parameterized constructor allows creation of initialized objects.
 Multiple constructors in the same class must have different parameter lists.
 Overloading increases flexibility for object creation.
Example:
#include <iostream>
//#include <new> // needed only if you want bad_alloc
using namespace std;
class Powers
{
int x;
public:
Powers() // default constructor
{
x = 0;
}
Powers(int n) // parameterized constructor
{
x = n;
}

Dept. of ISE, BMSIT&M 13


Arrays, Pointers, References
int getx()
{
return x;

}
void setx(int i)
{
x = i;

}
};

int main()
{
Powers ofTwo[] = {1, 2, 4, 8, 16}; // initialized array
Powers ofThree[5]; // uninitialized array
// set values for uninitialized array
ofThree[0].setx(1);
ofThree[1].setx(3);
ofThree[2].setx(9);
ofThree[3].setx(27);
ofThree[4].setx(81);

// dynamically allocated array


Powers *p = new Powers[5]; // calls default constructor
for(int i=0; i<5; i++)
p[i].setx(ofTwo[i].getx());
cout << "Powers of two: "; // display arrays
for(int i=0; i<5; i++)
cout << ofTwo[i].getx() << " ";
cout << "\nPowers of three: ";
for(int i=0; i<5; i++)
cout << ofThree[i].getx() << " ";
cout << "\nDynamic array: ";
for(int i=0; i<5; i++)
cout << p[i].getx() << " ";
delete [] p;
return 0;
}

Dept. of ISE, BMSIT&M 14


Arrays, Pointers, References

Default Function Arguments:


 A default function argument is a value assigned to a function parameter so that if the
caller does not provide an argument for that parameter, the function uses the default
value automatically.
Rules for Default Arguments
 Default values are specified only once, usually in the function prototype.
 Parameters with default values must be to the right of non-default parameters.
 You cannot provide a non-default parameter after a default parameter.
 Default arguments can be used in regular functions and constructors.
Example:
// Default argument = 0.0
void myfunc(double d = 0.0)
{
cout << "Value: " << d << endl;
}
int main()
{
myfunc(198.234); // explicit argument
myfunc(); // uses default argument 0.0
return 0;
}

Dept. of ISE, BMSIT&M 15


Arrays, Pointers, References

Function Overloading and Ambiguity in C++:


 Function overloading means defining multiple functions with the same name but
different parameter lists (number, type, or order of parameters).
Syntax:
int add(int a, int b);
double add(double a, double b);
 The compiler chooses which function to call based on the
type and number of arguments passed.

What is Ambiguity?
 Ambiguity occurs when the compiler cannot decide which overloaded function to call
i.e., when more than one version matches equally well.
 Such programs will not compile because the compiler reports an ambiguous call.
1. Ambiguity Due to Type Conversions:
 C++ automatically converts arguments between compatible types (like int → float
or char → int), which can cause confusion.
Example:
float myfunc(float i);
double myfunc(double i);
int main()
{
cout << myfunc(10.1); // OK: calls myfunc(double)
cout << myfunc(10); // Ambiguous: int → float or double?
}
2. Ambiguity Between char and unsigned char
Example:
char myfunc(unsigned char ch);
char myfunc(char ch);

Dept. of ISE, BMSIT&M 16


Arrays, Pointers, References

int main()
{
cout << myfunc('c'); // OK: char literal → myfunc(char)
cout << myfunc(88); // Ambiguous: 88 could be char or unsigned char

}
3. Ambiguity Due to Default Arguments
 If overloaded functions use default parameters, ambiguity can occur when a function
call matches multiple signatures.
Example:
int myfunc(int i);
int myfunc(int i, int j = 1);

int main()
{
cout << myfunc(4, 5); // OK: calls two-arg version
cout << myfunc(10);
// Ambiguous: one-arg version or two-arg version with j=1?
}

4. Ambiguity Due to References


 You cannot overload functions that differ only by reference vs value parameters.
Example:
void f(int x);
void f(int &x); // Error
int main()
{
int a = 10;
f(a); // Compiler confused — same syntax for both calls
}
o There’s no way for the compiler to distinguish whether the call should bind
to f(int) or f(int&).

Dept. of ISE, BMSIT&M 17


Arrays, Pointers, References
Cause of
Example Reason
Ambiguity
Type Conversion myfunc(10) → could be float or double Implicit conversions
myfunc(10) matches both myfunc(int)
Default Arguments Default parameter
and myfunc(int, int=1)
Reference
f(int) vs f(int&) Same call syntax
Parameters
Similar Narrow Multiple valid
char, unsigned char, int
Types conversions

How to Avoid Ambiguity


 Use explicit type casting while calling:
myfunc((float)10);
 Avoid unnecessary default parameters in overloaded functions.
 Avoid overloading with only reference/value differences.
 Use clear and distinct parameter types when overloading.

Dept. of ISE, BMSIT&M 18


Arrays, Pointers, References

Questions:
1. Write a detailed note on Arrays of Objects in C++. Explain how they are declared,
initialized, and accessed. Include examples for:
 Default constructor.
 Parameterized constructor (short and long form initialization)
2. Explain Pointers in C++ with emphasis on:
 Pointers to objects
 Pointers to derived types
 Pointers to class members.
Write suitable C++ programs for each case.
3. Explain the this pointer in detail. Discuss its need, uses, and role in resolving
naming conflicts and function chaining with examples.
4. What is Function Overloading? How is it implemented in C++? Discuss all the
causes of ambiguity with suitable programs and explain how to resolve them.
5. Explain in detail Constructor Overloading and Copy Constructors. Write a program
to demonstrate their use.
6. Write a detailed note on Default Function Arguments and Function Overloading.
Compare both mechanisms and explain how ambiguity can arise between them.
7. Discuss Function Overloading and Ambiguity in C++. Explain the following with
examples:
 Ambiguity due to type conversion
 Ambiguity due to default arguments
 Ambiguity due to references
 Ambiguity between similar types (char, unsigned char, int)
8. Explain the concept of Pointer to Class Member in C++. Include syntax, working,
and example programs to demonstrate:
 Pointer to data member
 Pointer to member function

Dept. of ISE, BMSIT&M 19

You might also like