0% found this document useful (0 votes)
24 views

Codes

The document discusses operator overloading in C++ using class templates and functors. It provides examples of overloading unary, binary, and stream operators. Function templates and class templates are demonstrated along with examples of passing template parameters and default template arguments.

Uploaded by

Tejaswi Ramineni
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)
24 views

Codes

The document discusses operator overloading in C++ using class templates and functors. It provides examples of overloading unary, binary, and stream operators. Function templates and class templates are demonstrated along with examples of passing template parameters and default template arguments.

Uploaded by

Tejaswi Ramineni
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
You are on page 1/ 27

Codes

#include <iostream>
using namespace std;

class Point {
public:
Point(int x, int y) : x(x), y(y) {}

// Overloading the stream insertion operator '<<'


friend ostream& operator<<(ostream& out, const Point& po) {
out << "(" << po.x << ", " << po.y << ")";
return out;
}

private:
int x;
int y;
};

int main() {
Point p(3, 5);

// Using the overloaded '<<' operator to display the Point object


cout << "Point coordinates: " << p << endl;

return 0;
}

// C++ program to show binary operator overloading using


// a Friend Function
#include <iostream>
using namespace std;

class Distance {
public:

int feet, inch;

Distance()
{
this->feet = 0;
this->inch = 0;
}

Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}

// Declaring friend function using friend keyword


friend Distance operator + (Distance&, Distance&);
};

// Implementing friend function with two parameters Call by reference


Distance operator+(Distance& d1,
Distance& d2)
{
// Create an object to return
Distance d3;

d3.feet = d1.feet + d2.feet;


d3.inch = d1.inch + d2.inch;

// Return the resulting object


return d3;
}
// Driver Code
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3;

// Use overloaded operator


d3 = d1 + d2;

cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch;
return 0;
}

// C++ program to show binary operator(+) overloading


#include <iostream>
using namespace std;

class Distance {
public:
int feet, inch;

Distance()
{
this->feet = 0;
this->inch = 0;
}

Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading (+) operator to perform addition of two distance
// object Call by reference
Distance operator+(Distance& d2)
{
// Create an object to return
Distance d3;
d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch;

// Return the resulting object


return d3;
}
};

// Driver Code
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3;

// Use overloaded operator


d3 = d1 + d2;

cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch;
return 0;
}

// C++ program to show unary operator(-) overloading


#include <iostream>
using namespace std;

class Distance {
public:
public:
int feet, inch;

// Constructor to initialize the object's value


Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}

// Overloading(-) operator to perform decrement operation of Distance object


void operator-()
{
feet--;
inch--;
cout << "\nFeet & Inches(Decrement): " <<
feet << "'" << inch;
}
};

// Driver Code
int main()
{
Distance d1(8, 9);

// Use (-) unary operator by single operand


-d1;
return 0;
}

#include <iostream>
using namespace std;
class MyClass {
public:
int data;
// Constructor
MyClass(int value) : data(value) {}

// Overloading >> operator as a friend function


friend istream& operator>>(istream& input, MyClass& obj) {
input >> obj.data;
return input;
}
};

int main() {
MyClass obj(0);

// Using the overloaded >> operator to input data into the object
cout << "Enter a value: ";
cin >> obj;

// Displaying the entered value


cout << "Entered value is: " << obj.data << std::endl;

return 0;
}

#include <iostream>
using namespace std;

class Point {
public:
Point(int x, int y) : x(x), y(y) {}

// Overloading the stream insertion operator '<<'


friend ostream& operator<<(ostream& out, const Point& po) {
out << "(" << po.x << ", " << po.y << ")";
return out;
}

private:
int x;
int y;
};

int main() {
Point p(3, 5);

// Using the overloaded '<<' operator to display the Point object


cout << "Point coordinates: " << p << endl;

return 0;
}

#include<iostream>
using namespace std;

class OpeDemo
{
public:
string str;

OpeDemo(string s)
{
str= s;
}

friend operator +(string &s,const OpeDemo &other)


{
string fullname = s+ other.str;
cout<<fullname;
}
};
int main()
{
string s("SREE");
OpeDemo obj2("VARSHA");
string name = s + obj2.str;
cout << name << endl; // Print the concatenated string.
}

#include<iostream>
using namespace std;

class OpeDemo
{
public:
string str;//data member

OpeDemo(string s)//constructor
{
str= s;
}

OpeDemo operator +(const OpeDemo &other)


{
string fullname = str+ other.str;
return OpeDemo(fullname);
}
};

int main()
{
OpeDemo obj1("SREE");
OpeDemo obj2("VARSHA");
OpeDemo obj3 = obj1 + obj2;
cout << obj3.str << endl; // Print the concatenated string.
}

#include<iostream>
using namespace std;

class Demo
{
public:

static void add(int a,int b)


{
cout<<"a+b="<<a+b<<endl;
}
void sub(int a,int b)
{
cout<<"a-b="<<a-b<<endl;

}
};

int main()
{
int a,b;
cout<<"Enter a and b values:"<<endl;
cin>>a>>b;
Demo obj;//object creation
Demo::add(a,b);
obj.sub(a,b);
return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>

// Functor for squaring each element


struct Square {
int operator()(int element) const {
return element * element;
}
};

int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::vector<int> squaredNumbers(numbers.size());

// Using transform with a functor to square each element


std::transform(numbers.begin(), numbers.end(), squaredNumbers.begin(), Square());

// Printing the squared numbers


for (const auto& num : squaredNumbers) {
std::cout << num << " ";
}

return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>

// Functor for printing each element


struct PrintElement {
void operator()(int element) const {
std::cout << element << " ";
}
};
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};

// Using for_each with a functor


std::for_each(numbers.begin(), numbers.end(), PrintElement());

return 0;
}

#include <iostream>
#include <vector>
using namespace std;
int main() {
// Declare a vector of integers
vector<int> myVector ;

// Add elements to the vector


myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);

// Access elements using index


cout << "First element: " << myVector[0] << endl;

// Iterate through the vector


cout << "Vector elements: ";
for (int i = 0; i < myVector.size(); ++i) {
cout << myVector[i] << " ";
}

// Vector size
cout << "\nVector size: " << myVector.size() << endl;
return 0;
}

#include <iostream>
using namespace std;

// Class template with multiple and default parameters


template <class T, class U, class V = char>
class ClassTemplate {
private:
T var1;
U var2;
V var3;

public:
ClassTemplate(T v1, U v2, V v3) : var1(v1), var2(v2), var3(v3) {} // constructor

void printVar() {
cout << "var1 = " << var1 << endl;
cout << "var2 = " << var2 << endl;
cout << "var3 = " << var3 << endl;
}
};

int main() {
// create object with int, double and char types
ClassTemplate<int, double> obj1(7, 7.7, 'c');
cout << "obj1 values: " << endl;
obj1.printVar();

// create object with int, double and bool types


ClassTemplate<double, char, bool> obj2(8.8, 'a', false);
cout << "\nobj2 values: " << endl;
obj2.printVar();
return 0;
}

#include <iostream>
using namespace std;

template <class T>


class Calculator {
private:
T num1, num2;

public:
Calculator(T n1, T n2) {
num1 = n1;
num2 = n2;
}

void displayResult() {
cout << "Numbers: " << num1 << " and " << num2 << "." << endl;
cout << num1 << " + " << num2 << " = " << add() << endl;
cout << num1 << " - " << num2 << " = " << subtract() << endl;
cout << num1 << " * " << num2 << " = " << multiply() << endl;
cout << num1 << " / " << num2 << " = " << divide() << endl;
}

T add() { return num1 + num2; }


T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() { return num1 / num2; }
};

int main() {
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();

cout << endl


<< "Float results:" << endl;
floatCalc.displayResult();

return 0;
}

// C++ program to demonstrate the use of class templates

#include <iostream>
using namespace std;

// Class template
template <class T>
class Number {
private:
// Variable of type T
T num;

public:
Number(T n) : num(n) {} // constructor

T getNum() {
return num;
}
};

int main() {

// create object with int type


Number<int> numberInt(7);
// create object with double type
Number<double> numberDouble(7.7);

cout << "int Number = " << numberInt.getNum() << endl;


cout << "double Number = " << numberDouble.getNum() << endl;

return 0;
}

#include <iostream>
using namespace std;

template <typename T>


T add(T num1, T num2) {
return (num1 + num2);
}

int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout <<result1 << endl;

// calling with double parameters


result2 = add<double>(2.2, 3.3);
cout <<result2 << endl;

return 0;
}

//aggregation demo
#include <iostream>
#include <string>

class Department {
public:
Department(std::string name) : name(name) {
}

std::string getName() const {


return name;
}

private:
std::string name;
};

class University {
public:
University(std::string name) : name(name), departmentCount(0), departments(NULL) {
}

void addDepartment(const Department& department) {


Department** temp = new Department*[departmentCount + 1];
for (int i = 0; i < departmentCount; ++i) {
temp[i] = departments[i];
}
temp[departmentCount] = new Department(department);
delete[] departments;
departments = temp;
++departmentCount;
}

void displayDepartments() {
std::cout << "Departments at " << name << ":\n";
for (int i = 0; i < departmentCount; ++i) {
std::cout << " - " << departments[i]->getName() << "\n";
}
}

~University() {
for (int i = 0; i < departmentCount; ++i) {
delete departments[i];
}
delete[] departments;
}

private:
std::string name;
int departmentCount;
Department** departments; // Aggregation: University has Departments (pointers)
};

int main() {
Department dept1("Computer Science");
Department dept2("Physics");
Department dept3("Mathematics");

University myUniversity("Example University");


myUniversity.addDepartment(dept1);
myUniversity.addDepartment(dept2);
myUniversity.addDepartment(dept3);

myUniversity.displayDepartments();

return 0;
}

//The following example illustrates the ambiguous situation caused by a diamond


//structured inheritance.

#include <iostream>
using namespace std;
// base class
class Base_class
{
public:
int x;
};

// class 1
class class_1 : public Base_class
{
public:
int y;
};

// class 2

class class_2 : public Base_class


{
public:
int z;
};

// derived class 3

class derived_class : public class_1, public class_2


{
public:
int sum;
};

int main()
{
// create an object of the derived_class
derived_class obj;
obj.class_1::x = 10;//

//no ambiguous // obj.x = 10; // ambiguous

obj.y = 20;

obj.z = 30;

obj.sum = obj.class_1::x + obj.y + obj.z; //obj.sum = obj.class_1::x + obj.y + obj.z;

cout << "The sum is: " << obj.sum << "\n\n";

return 0;

#include <iostream>
using namespace std;
// base class
class Base_class
{
public:
int x;
};
// class 1
class class_1 : virtual public Base_class
{
public:
int y;
};
// class 2
class class_2 : virtual public Base_class
{
public:
int z;
};
// derived class 3
class derived_class : public class_1, public class_2
{
public:
int sum;
};
int main()
{
// create an object of the derived_class
derived_class obj;
obj.x = 10; // it is now unambiguous
obj.y = 20;
obj.z = 30;
obj.sum = obj.x + obj.y + obj.z;
cout << "The sum is: " << obj.sum << "\n\n";
return 0;
}

//The following code displays the working of private visibility mode


//with all three access specifiers of the base class:
#include<iostream>
using namespace std;
class base_class

private:

//class member

int base_private;

protected:
//class member

int base_protected;

public:

//class member

int base_public;

};

class derived_class : private base_class

private:

int derived_private;

// int base_private;

// int base_protected;

// int base_public

protected:

int derived_protected;

public:

int derived_public;

};
int main()

// Accessing members of base_class using object of the derived_class:

derived_class obj;

obj.base_private; // Not accessible

obj.base_protected; // Not accessible

obj.base_public; // Not Accessible

//The following code displays the working of protected visibility mode


//with all three access specifiers of the base class:
#include<iostream>
using namespace std;
class base_class

private:

//class member

int base_private;

protected:

//class member

int base_protected;
public:

//class member

int base_public;

};

class derived_class : protected base_class

private:

int derived_private;

// int base_private;

protected:

int derived_protected;

// int base_protected;

// int base_public

public:

int derived_public;

};

int main()

{
// Accessing members of base_class using object of the derived_class:

derived_class obj;

obj.base_private; // Not accessible

obj.base_protected; // Not accessible

obj.base_public; // Not Accessible

//public visibility mode demo

//The following code displays the working of public visibility mode


//with all three access specifiers of the base class:
#include<iostream>
using namespace std;

class base_class

private:

//class member

int base_private;

protected:

//class member
int base_protected;

public:

//class member

int base_public;

};

class derived_class : public base_class

private:

int derived_private;

// int base_private;

protected:

int derived_protected;

// int base_protected;

public:

int derived_public;

// int base_public;

};

int main()
{

// Accessing members of base_class using object of the //derived_class:

derived_class obj;

obj.base_private; // Not accessible

obj.base_protected; // Not accessible

obj.base_public; // Accessible

//Inheritance demo
#include <iostream>
using namespace std;
// base class
class Animal
{
public:
// constructor of the base class
Animal()
{
cout << "I am an animal.-Base class\n";
}

};

// derived class
class Pet: public Animal
{
public:
// constructor of the derived class
Pet()
{
cout << "I am a pet.-Derived class\n";
}

};

int main()
{
// create an object of the child's class
Pet obj;

return 0;
}

You might also like