0% found this document useful (0 votes)
25 views15 pages

Unit - 2 C++ - Final

C++ Final basics learning

Uploaded by

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

Unit - 2 C++ - Final

C++ Final basics learning

Uploaded by

ramur2000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit – 2

Overloading in C++:

The process of using a single identifier for naming multiple methods


in a class having a different number of input or output parameters
is known as overloading.

Types of overloading in C++ are:

o Function overloading
o Operator overloading

C++ Function Overloading

 This is the most common type of overloading. It involves


defining multiple functions in the same scope with the same name
but different parameter lists.
 The compiler selects the appropriate function to call based on
the number and types of arguments provided during the function
call.
 Function overloading is determined at compile-time.

Example:
1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b)
6. { return a + b; }
7. static int add(int a, int b, int c)
8. { return a + b + c; }
9. };
10. int main(void) {
11. Cal C; // class object decla
ration.
12. cout<<C.add(10, 20)<<endl;
13. cout<<C.add(12, 20, 23);
14. return 0;
15. }

Default Arguments:

 Default arguments in C++ allow us to provide default values


for parameters in a function.
 When a function with default arguments is called, no need to
specify values for those parameters, and the default values will
be used.

Example:

#include <iostream>
// Function with two parameters, one with a default value
int add(int a, int b = 0)
{
return a + b;
}
// Function with three parameters, two with default values
int add(int a, int b = 0, int c = 0)
{
return a + b + c;
}
int main()
{
cout << add(2) << endl; // Calls the 1st function with
default value
cout << add(2, 3) <<endl; // Calls the 1st function specifying
'b' value
cout << add(1, 2, 3) ; // Calls the 2 nd function, with values for
'b' and 'c'
return 0;
}
Constructor Overloading in C++
 Overloaded constructors have the same name of the class but
with different number of arguments.
 Depending upon the number and type of arguments passed,
the corresponding constructor is called.

Example:
// C++ program to demonstrate constructor overloading
#include <iostream>
using namespace std;
class Person {
private:
int age;
public:
Person() // 1. Constructor with no arguments
{ age = 20; }
Person(int a) // 2. Constructor with one argument
{ age = a; }

int getAge() {
return age;
}
};
int main() {
Person person1, person2(45);
cout << "Person1 Age = " << person1.getAge() << endl;
cout << "Person2 Age = " << person2.getAge() << endl;
return 0;
}
Operator Overloading:
 Operator overloading is one of the best features of C++.
 By overloading the operators, we can give additional meaning
to the operators.
 The mechanism of giving special meaning to an operator is
known as operator overloading.
 It has the ability to redefine the behaviour of Operators such
as
+, -, *, /, =, ==, <, etc.,
Syntax for C++ Operator Overloading

To overload an operator, we use a special operator function. We


define the function inside the class.

class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};

Rules to create Operator Overloading:


1. The Overload operator must have at least one operand of user-
defined type.
2. We can only overload the existing operators, Can’t overload
new operators.
3. We cannot change the basic meaning of the operator.

Operators which Cannot be overloaded?

 Conditional [?:],
 Size of Operator (size of),
 scope(::),
 Member selector(.),
 member pointer selector(.*) and
 the casting operators.

Types of Operator Overloading


 Unary Operators Overloading
 Binary Operator overloading

Unary operators:
 Operators which work on a single operand are called unary
operators.
 Examples: Increment operators(++), Decrement
operators(–),unary minus operator(-), Logical not operator(!)
etc…

Binary operators:
 Operators which works on Two operands are called binary
operator.

Example for Unary Operator Overloading:


#include<iostream>
using namespace std;
class UnaryOverload
{
int hr, min;
public:
void in()
{
cout<<"\n Enter the time: \n";
cin>>hr;
cout<<endl;
cin>>min;
}
void operator++(int) //Overload Unary Increment
{
hr++;
min++;
}
void operator--(int) //Overload Unary Decrement
{
hr--;
min--;
}
void out()
{
cout<<"\nTime is "<<hr<<"hr "<<min<<"min";

}
};
int main()
{
UnaryOverload ob;
ob.in();
ob++;
cout<<"\n\n After Incrementing : ";
ob.out();
ob--;
ob--;
cout<<"\n\n After Decrementing : ";
ob.out();
return 0;
}
Output
Enter the time:
5
56
After Incrementing:
Time is 6hr 57 mins
After Decrementing:
Time is 4hr 55 min

Example for Binary Operator Overloading:

#include <iostream>
class Vector {
private:
int x, y;
public:
Vector(int x, int y) : x(x), y(y) {}
// Overloading the + operator for vector addition
Vector operator+(const Vector& other) const {
return Vector(x + other.x, y + other.y);
}
// Method to display vector coordinates
void display() const {
std::cout << "x: " << x << ", y: " << y << std::endl;
}
};

int main() {
Vector v1(2, 3);
Vector v2(1, -1);
Vector result = v1 + v2; // Using the overloaded + operator
std::cout << "Resultant vector: ";
result.display();
return 0;
}

Overloading an operator as a member function:


A member operator function takes this general form:

ret-type class-name::operator#(arg-list)

{ // operations }

In C++, you can overload an operator as a member function of a


class.

When you overload an operator as a member function, the left


operand is implicitly the object on which the function is called, and
the right operand is passed as an argument.

Here's an example using the + operator:


#include <iostream>
Class MyClass {
Private:
int value;
public:
MyClass (int val) : value(val) {}
// overloading the '+' operator as a member function
MyClass operator+(const MyClass& other) const
{ return MyClass(value + other.value); }
// Member function to display the value
void display() const
{ cout << "Value: " << value << endl; }
};
int main() {
MyClass obj1(5) , obj2(10);
// Using the overloaded '+' operator
MyClass result = obj1 + obj2;
result.display(); // Output: Value: 15
return 0;
}

Overloading an operator as a friend function

The Friend function in C++ using operator overloading offers better


flexibility to the class.

The Friend functions are not a member of the class and hence they
do not have 'this' pointer.

When we overload a unary operator, we need to pass one


argument. When we overload a binary operator, we need to pass
two arguments.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int img;
public:
Complex (int r = 0, int i = 0)
{
real = r;
img = i;
}
void Display ()
{
cout << real << "+i" << img;
}
friend Complex operator + (Complex c1, Complex c2);
};
Complex operator + (Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;
}

int main ()
{
Complex C1(5, 3), C2(10, 5), C3;
C1.Display();
cout << " + ";
C2.Display();
cout << " = ";
C3 = C1 + C2;
C3.Display();
}

Overloading the Operator [] (Subscripting Operator)


 The Subscript or Array Index Operator is denoted by ‘[]’.
 This operator is generally used with arrays to retrieve and
manipulate the array elements.
 This operator can be overloaded to enhance the existing
functionality of C++ arrays.

#include <iostream>
using namespace std;

const int SIZE = 10;


class safearay {
private:
int arr[SIZE];
public:
safearay() {
register int i;
for(i = 0; i < SIZE; i++) {
arr[i] = i;
}
}
int &operator[](int i) {
if( i > SIZE ) {
cout << "Index out of bounds" <<endl;
// return first element.
return arr[0];
}
return arr[i];
}
};
int main() {
safearay A;
cout << "Value of A[2] : " << A[2] <<endl;
cout << "Value of A[5] : " << A[5]<<endl;
cout << "Value of A[12] : " << A[12]<<endl;
return 0;
}
Overloading the operator () (Function call operator)

 The function call operator () can be overloaded for objects of


class type.
 When we overload ( ), it is not creating a new way to call a
function.
 Instead, an operator function is created and values can be
passed to the parameters.

#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
// overload function call
Distance operator()(int a, int b, int c) {
Distance D;
D.feet = a + c + 10; // just a random calculation
D.inches = b + c + 100 ;
return D;
}
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};
int main() {
Distance D1(11, 10), D2;
cout << "First Distance : ";
D1.displayDistance();
D2 = D1(10, 10, 10); // invoke operator()
cout << "Second Distance :";
D2.displayDistance();
return 0;
}

Overloading the operator -> (Class Member access operator)

The -> operator is used to access members of an object through


pointers.

Here's how operator overloading with the -> operator works in C+


+:

Member Access Operator ->:

Normally, -> is used with pointers to access members of an object.

Ex: MyClass *ptr = new MyClass();

ptr->memberFunction();

Here, ptr->memberFunction() is equivalent to


(*ptr).memberFunction(),

where ptr is a pointer to an object of type MyClass.

Overloading -> Operator:

When we overload ->, we can provide a custom definition for what


happens when the -> operator is used with objects of your class.
Overloading the Comma Operator

 The purpose of comma operator is to string together several


expressions.
 The value of a comma-separated list of expressions is the
value of the right-most expression.
 The values of the other expressions will be discarded.
 The expression on the right side will become the value of the
entire comma-separated expression.
 For example − var = (count = 19, incr = 10, count+1);
 Here first assigns count the value 19, assigns incr the value 10,
then adds 1 to count, finally, assigns var the value of count+1,
which is 20.

#include <iostream>
using namespace std;
int main() {
int i, j;
j = 10;
i = (j++, j+100, 999+j);
cout << i;
return 0;
}

it produces the following result −

1010
---------------------------------------------------
Conversion Functions

It is a process of converting data of one type to another type. This is


known as type conversion.

There are two types of type conversion in C++.

1. Implicit Conversion

2. Explicit Conversion (also known as Type Casting)

Implicit Type Conversion

 This type of conversion is automatically done by the compiler.


 This type of conversion is also known as automatic conversion.
Example:

Float b=9.5;
Int x;
X=b;
Cout <<x;
Output: 9

Explicit Conversion :

When the user manually changes data from one type to another
type is known as explicit conversion. It is also known as Type
Casting.

Example :
Int a=15;
Double x:
X= double(a);
Cout<<x;
Output: 15.000

There are three major ways in which we can use explicit conversion
in C++. They are:

1. C-style type casting (also known as cast notation)


2. Function notation (also known as old C++ style type casting)
3. Type conversion operators
Data Loss During Conversion (Narrowing Conversion)

 Conversion from one data type to another will lead to data


loss.
 This happens when data of a larger type is converted to data
of a smaller type.

You might also like