Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

OOPS Unit 1 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

OBJECT ORIENTED

PROGRAMMING
Unit 1

Prepared By
S. Janani ,AP/CSE
SVCE.
What Are OOPS Concepts In C++?
➢ OOPs, or Object-oriented programming is an approach or a programming pattern where the
programs are structured around objects rather than functions and logic. It makes the data
partitioned into two memory areas, i.e., data and functions, and helps make the code flexible
and modular.
➢ Object-oriented programming mainly focuses on objects that are required to be manipulated.
In OOPs, it can represent data as objects that have attributes and functions.

Why Do You Need Object-Oriented Programming?

➢ The earlier approaches to programming were not that good, and there were several
limitations as well. Like in procedural-oriented programming, you cannot reuse the code
again in the program, and there was the problem of global data access, and the approach
couldn’t solve the real-world problems very well.
➢ In object-oriented programming, it is easy to maintain the code with the help of classes and
objects. Using inheritance, there is code reusability, i.e., you don’t have to write the same
code again and again, which increases the simplicity of the program. Concepts like
encapsulation and abstraction provide data hiding as well.
Basic Object-Oriented Programming (OOPS) Concept in C++(16m)

There are some basic concepts that act as the building blocks of OOPs.
1. Classes
2. Objects
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding

1. Object
➢ An Object can be defined as an entity that has a state and behavior, or in other words,
anything that exists physically in the world is called an object. It can represent a dog, a
person, a table, etc.
➢ An object means the combination of data and programs, which further represent an entity.

Syntax Of Object : Classname Objectname;


2. Classes
➢ Class can be defined as a blueprint of the object. It is basically a collection of objects
which act as building blocks.
➢ A class contains data members (variables) and member functions. These member
functions are used to manipulate the data members inside the class.
Example1 of Class and Object

#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
Example 2 of Class and Object
#include <iostream>
using namespace std; int main(void) {
class Student { Student s1; //creating an object of Student
public: Student s2; //creating an object of Student
int id;//data member (also instance variable) s1.insert(201, "Sonoo");
string name;//data member(also instance variable) s2.insert(202, "Nakul");
void insert(int i, string n) s1.display();
{ s2.display();
id = i; return 0;
name = n; }
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
3. Abstraction

Abstraction helps in the data hiding process. It helps in displaying the essential features without
showing the details or the functionality to the user.
It avoids unnecessary information or irrelevant details and shows only that specific part which the
user wants to see.
4. Encapsulation

The wrapping up of data and functions together in a single unit is known as encapsulation. It can be
achieved by making the data members' scope private and the member function’s scope public to
access these data members. Encapsulation makes the data non-accessible to the outside world.
5. Inheritance
Inheritance is the process in which two classes have an is-a relationship among each other and
objects of one class acquire properties and features of the other class. The class which inherits
the features is known as the child class, and the class whose features it inherited is called the
parent class. For example, Class Vehicle is the parent class, and Class Bus, Car, and Bike are
child classes.
6. Polymorphism
Polymorphism means many forms. It is the ability to take more than one form. It is a feature
that provides a function or an operator with more than one definition. It can be implemented
using function overloading, operator overload, function overriding, virtual function.
Advantages of OOPs
There are various advantages of object-oriented programming.
➢ OOPs provide reusability to the code and extend the use of existing classes.
➢ In OOPs, it is easy to maintain code as there are classes and objects, which helps in making it
easy to maintain rather than restructuring.
➢ It also helps in data hiding, keeping the data and information safe from leaking or getting
exposed.
➢ Object-oriented programming is easy to implement.
Access Specifiers
In C++, there are three access specifiers:
•public - members are accessible from outside the class
•private - members cannot be accessed (or viewed) from outside the class
•protected - members cannot be accessed from outside the class.

class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
// C++ program to demonstrate private
#include<iostream>
using namespace std;
class Circle
{ private:
double radius;
public:
double compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
obj.radius = 1.5;
cout << "Area is:" << obj.compute_area();
return 0;
}
// C++ program to demonstrate private

#include<iostream> int main()


{
using namespace std; Circle obj;
class Circle // trying to access private data member
{ // directly outside the class
private: obj.compute_area(1.5);
return 0;
double radius;
}
public:
void compute_area(double r)
{ // member function can access private
radius = r;
double area = 3.14*radius*radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
}
};
References in C++
When a variable is declared as a reference, it becomes an alternative name for an existing
variable. A variable can be declared as a reference by putting ‘&’ in the declaration.
#include <iostream>
using namespace std;
int main()
{ int x = 10;
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << '\n';
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << '\n';
return 0;
}
Example1 of Default Constructors

class Cube class Cube


{ {
public: public:
int side; int side;
Cube() };
{
side = 10; int main()
} {
}; Cube c;
cout << c.side;
int main() }
{
Cube c;
cout << c.side;
}
Example2 of Default Constructors
class A
class A {
{ public:
public: int i;
int x; A(); // constructor declared
// constructor };
A()
{ // constructor definition
// object initialization A::A()
} {
}; i = 1;
}

While defining a contructor you must remeber that the name of constructor will be same
as the name of the class, and contructors will never have a return type.
Constructors can be defined either inside the class definition or outside class definition
using class name and scope resolution :: operator.
Example1 of Parameterized Constructors
class Cube
{
public:
int side;
Cube(int x)
{
side=x; 10 20 30
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
C++ Copy Constructor

A Copy constructor is an overloaded constructor used to declare and initialize an object


from another object.
Copy Constructor is of two types:
•Default Copy constructor: The compiler defines the default copy constructor. If the
user defines no copy constructor, compiler supplies its constructor.
•User Defined constructor: The programmer defines the user-defined constructor.
Copy Constructor in C++
Copy Constructors is a type of constructor which is used to create a copy of an
already existing object of a class type. It is usually of the form X (X&), where X
is the class name. The compiler provides a default Copy Constructor to all the
classes.
Syntax of Copy Constructor
Classname(const classname & objectname)
{
....
}
As it is used to create an object, hence it is called a constructor. And, it creates a
new object, which is exact copy of the existing copy, hence it is called copy
constructor.
#include<iostream> Example1 of Copy Constructors
using namespace std; and Parametrized Constructors /* main function */
class Samplecopyconstructor int main()
{ {
private: Samplecopyconstructor obj1(10, 15); // Normal
int x, y; //data members constructor
public: Samplecopyconstructor obj2 = obj1; // Copy
Samplecopyconstructor(int x1, int y1) constructor
{ cout<<"Normal constructor : ";
x = x1; obj1.display();
y = y1; cout<<"Copy constructor : ";
} obj2.display();
Samplecopyconstructor (const Samplecopyconstructor &sam) return 0;
{ }
x = sam.x;
y = sam.y;
}
void display()
{
cout<<x<<" "<<y<<endl;
}
};
Functions

➢ A function is a block of code which only runs when it is called.


➢ You can pass data, known as parameters, into a function.
➢ Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute
code. But you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function,
followed by parentheses ():

void myFunction()
{
// code to be executed
}
Call a Function

Declared functions are not executed immediately. They are "saved for later use", and
will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is
called:
Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


Function Declaration and Definition
A C++ function consist of two parts:
•Declaration: the return type, the name of the function, and parameters (if any)
•Definition: the body of the function (code to be executed)
// Function
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function
void myFunction() {
cout << "I just got executed!";
}

Try it Yourself »
Friend Function in C++ (8m)
As we already know that in an object-oriented programming language, the members of the
class can only access the data and functions of the class but outside functions cannot access
the data of the class. There might be situation that the outside functions need to access the
private members of the class so in that case, friend function comes into the picture.
What is a friend function?
A friend function is a function of the class defined outside the class scope but it has the right
to access all the private and protected members of the class.
The friend functions appear in the class definition but friends are the member functions.
➢ The friend function is declared using friend keyword.
➢ It is not a member of the class but it is a friend of the class.
➢ As it is not a member of the class so it can be defined like a normal function.
➢ Friend functions do not access the class data members directly but they pass an object
as an argument.
➢ It is like a normal function.
➢ If we want to share the multiple class's data in a function then we can use the friend
function.
Characteristics of a Friend function:
•The function is not in the scope of the class to which it has been declared as a
friend.
•It cannot be called using the object as it is not in the scope of that class.
•It can be invoked like a normal function without using the object.
•It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
•It can be declared either in the private or the public part.

Why do we need a friend function in C++?


•Friend function in C++ is used when the class private data needs to be
accessed directly without using object of that class.
•Friend functions are also used to perform operator overloading. As we
already know about the function overloading, operators can also be
overloaded with the help of operator overloading.
Syntax of Friend Function
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function
};

In the above declaration, the friend function is preceded by the keyword friend.
The function can be defined anywhere in the program like a normal C++ function.
The function definition does not use either the keyword friend or scope resolution
operator.
Example 1 Friend Function – Addition of 2Nos(8m)
#include <iostream> int main()
using namespace std; {
class Calculator Calculator c;
{ int firstNum, secondNum;
private: int first, second; cout << "Enter the first number: " << endl;
friend int addNumbers(Calculator, int i, int j); cin >> firstNum;
int Add() cout << "Enter the second number: " << endl;
{ cin >> secondNum;
return first + second; cout << "Sum: " << addNumbers(c, firstNum,
} secondNum) << endl;
}; }
int addNumbers(Calculator c, int firstNum, int
secondNum)
{
c.first = firstNum;
c.second = secondNum;
return c.Add();
}
C++ Overloading (Function and Operator) (16 m)
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload Methods, Constructors,
and Indexed properties It is because only these members have parameters.
Types of overloading in C++ are:
1. Function overloading
2. Operator overloading

C++ Function Overloading (8m)


Function Overloading is defined as the process of having two or more function
with the same name, but different in parameters is known as function overloading in
C++. In function overloading, the function is redefined by using either different types
of arguments or a different number of arguments. It is only through these differences
compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the
program because you don't need to use different names for the same action.
Example 2 Program of function overloading when number of arguments vary.
#include <iostream>
using namespace std; int main(void)
class Cal {
{ Cal C; // class object
public: declaration. cout<<C.add(10, 20)<<endl;
static int add(int a,int b) cout<<C.add(12, 20, 23);
{ return 0;
return a + b; }
}
static int add(int a, int b, int c)
{
return a + b + c; Output :
}
}; 30 55
Example 2 Program of function overloading with different types of arguments.

#include<iostream> int main()


using namespace std; {
int mul(int,int); int r1 = mul(6,7);
float mul(float,int); float r2 = mul(0.2,3);
int mul(int a,int b) std::cout << "r1 is : " <<r1<< std::endl;
{ std::cout <<"r2 is : " <<r2<< std::endl;
return a*b; return 0;
} }
float mul(double x, int y)
{
return x*y;
} Output :
r1 is : 42 r2 is :
0.6
Dynamic memory allocation in C++ (8m)

There are times where the data to be entered is allocated at the time of execution. For example, a
list of employees increases as the new employees are hired in the organization and similarly
reduces when a person leaves the organization. This is called managing the memory. So now, let
us discuss the concept of dynamic memory allocation

Memory allocation

Reserving or providing space to a variable is called memory allocation. For storing the data,
memory allocation can be done in two ways -
➢ Static allocation or compile-time allocation - Static memory allocation means providing
space for the variable. The size and data type of the variable is known, and it remains
constant throughout the program.
➢ Dynamic allocation or run-time allocation - The allocation in which memory is allocated
dynamically. In this type of allocation, the exact size of the variable is not known in advance.
Pointers play a major role in dynamic memory allocation.
Why Dynamic memory allocation?

Dynamically we can allocate storage while the program is in a running state, but variables cannot
be created "on the fly". Thus, there are two criteria for dynamic memory allocation

1. A dynamic space in the memory is needed.


2. Storing the address to access the variable from the memory
Similarly, we do memory de-allocation for the variables in the memory.

In C++, memory is divided into two parts -


1. Stack - All the variables that are declared inside any function take memory from the stack.
2. Heap - It is unused memory in the program that is generally used for dynamic memory
allocation.
Dynamic memory allocation using the new operator

To allocate the space dynamically, the operator new is used. It means creating a request
for memory allocation on the free store. If memory is available, memory is initialized,
and the address of that space is returned to a pointer variable.

Syntax
Pointer_variable = new data_type;
The pointer_varible is of pointer data_type. The data type can be int, float, string, char,
etc.

Example 1
int *m = NULL // Initially we have a NULL pointer
m = new int // memory is requested to the variable
It can be directly declared by putting the following statement in a line -
int *m = new int
Initialize memory
We can also initialize memory using new operator.
For example 2

int *m = new int(20);


Float *d = new float(21.01);

Allocate a block of memory : We can also use a new operator to allocate a block(array) of a
particular data type. For example
int *arr = new int[10]
Here we have dynamically allocated memory for ten integers which also returns a pointer to the
first element of the array. Hence, arr[0] is the first element and so on.
Note
•The difference between creating a normal array and allocating a block using new normal arrays is
deallocated by the compiler. Whereas the block is created dynamically until the programmer
deletes it or if the program terminates.
•If there is no space in the heap memory, the new request results in a failure throwing an
exception(std::bad_alloc) until we use nonthrow with the new operator. Thus, the best practice is to
first check for the pointer variable.
Delete operator
We delete the allocated space in C++ using the delete operator.
Syntax
delete pointer_variable_name
Example 3
delete m; // free m that is a variable
delete [] arr; // Release a block of memory
Example 4 to Demonstrate Dynamic Memory Allocation
The program will show the use of new and delete
#include <iostream> // Request block of memory// using new operator
using namespace std; float *f = new float(75.25);
int main () cout<< "Value of f: " << *f <<endl;
{ // Pointer initialization to null // Request block of memory of size
int* m = NULL; // Request memory for the variable int size = 5;
m = new(nothrow) int; // using new operator int *arr = new(nothrow) int[size];
if (!m) if (!arr)
cout<< "allocation of memory failed\n"; cout<< "allocation of memory failed\n";
else else
{ {
// Store value at allocated address for (int i = 0; i< size; i++)
*m=29; arr[i] = i+1;
cout<< "Value of m: " << *m <<endl; cout<< "Value store in block of memory: ";
} for (int i = 0; i< size; i++)
cout<<arr[i] << " ";
}
// freed the allocated memory
delete m;
delete f;
// freed the block of allocated memory
delete[] arr;
return 0;
}

Output :
Value of m: 29
Value of f: 75.25
Value store in block of memory: 1 2 3 4 5
Static Member Functions (2m or 8m)
➢ We can define class members static using static keyword. When we declare a member of a class
as static it means no matter how many objects of the class are created, there is only one copy of
the static member.
➢ A static member is shared by all objects of the class. All static data is initialized to zero when the
first object is created, if no other initialization is present. We can't put it in the class definition but
it can be initialized outside the class as done in the following example by redeclaring the static
variable, using the scope resolution operator :: to identify which class it belongs to.

➢ By declaring a function member as static, you make it independent of any particular object of the
class. A static member function can be called even if no objects of the class exist and
the static functions are accessed using only the class name and the scope resolution operator ::.
➢ A static member function can only access static data member, other static member functions and
any other functions from outside the class.
➢ Static member functions have a class scope and they do not have access to the this pointer of the
class. You could use a static member function to determine whether some objects of the class
have been created or not.
What is the difference between static and non-static variables?
Static Variables:
A static variable is associated with the class has only one copy per class but not for each object. An
instance of a class does not have static variables.
Static variables can be accessed by static or instance methods
Memory is allocated when the class is loaded in context area at run time.

Non-Static Variables:
Non-static variables will have one copy each per object. Each instance of a class will have one copy
of non-static variables.
Instance variables can be accessed only by the instance methods.
Instance variables are allocated at compile time.

What is the difference between static and non-static variables?


A static variable is shared among all instances of a class.
A non-static variable is specific to a single instance of that class.

Eg: A static variable can be shared by all users for the current running system. It’s a globally available
value and can be used by all users.
Example 1 Static variable
#include <iostream> private:
using namespace std; double length; // Length of a box
class Box { double breadth; // Breadth of a box
public: static int objectCount; double height; // Height of a box
Box(double l = 2.0, double b = 2.0, double h = 2.0) };
{ cout <<"Constructor called." << endl;
// Initialize static member of class Box
length = l;
int Box::objectCount = 0;
breadth = b;
int main(void) {
height = h;
Box Box1(3.3, 1.2, 1.5); // Declare box1
// Increase every time object is created
Box Box2(8.5, 6.0, 2.0); // Declare box2
objectCount++;
cout << "Total objects: " << Box::objectCount <<
} endl;
double Volume() { return 0;
return length * breadth * height; }
}
Example 2 :Static Function Members static int getCount() {
#include <iostream> return objectCount;
using namespace std; }
class Box { private:
public: double length; // Length of a box
static int objectCount; double breadth; // Breadth of a box
// Constructor definition double height; // Height of a box
Box(double l = 2.0, double b = 2.0, double h = 2.0) };
{ int Box::objectCount = 0;
cout <<"Constructor called." << endl; int main(void) {
length = l; // Print total number of objects before creating object.
breadth = b; cout << "Inital Stage Count: " << Box::getCount() <<
height = h; endl;
// Increase every time object is created Box Box1(3.3, 1.2, 1.5); // Declare box1
objectCount++; Box Box2(8.5, 6.0, 2.0); // Declare box2
} // Print total number of objects after creating object.
double Volume() { cout << "Final Stage Count: " << Box::getCount() <<
return length * breadth * height; endl;
} return 0;
}
Applications :
1. Modify the passed parameters in a function: If a function receives a reference to a variable, it
can modify the value of the variable. For example, the following program variables are swapped
using references.
2. Avoiding a copy of large structures: Imagine a function that has to receive a large object. If
we pass it without reference, a new copy of it is created which causes wastage of CPU time and
memory. We can use references to avoid this.

3. In For Each Loop to modify all objects: We can use references in for each loop to modify
all elements.

4. For Each Loop to avoid the copy of objects: We can use references in each loop to avoid a
copy of individual objects when objects are large.
Proxy Classes : The Proxy class is basically the Proxy design pattern. In this pattern an object
provides a modified interface for another class. Let us see one example.

class BinArray {
int arr[10];
int & operator[](int i) {
//Put some code here
}
};

In this code, there is no condition checking. But we want the operator[] to complain if we put
something like arr[1] = 98. But this is not possible, because it is checking the index not the value. Now
we will try to solve this using proxy pattern.
What is Operator Overloading? (8m)
Using operator overloading in C++, you can specify more than one meaning for an operator in one
scope. The purpose of operator overloading is to provide a special meaning of an operator for a user-
defined data type.
With the help of operator overloading, you can redefine the majority of the C++ operators. You can
also use operator overloading to perform different operations using one operator.
Syntax
To overload a C++ operator, you should define a special function inside the Class as follows:

class class_name
{
... .. ...
public
return_type operator symbol (argument(s))
{
... .. ...
}
... .. ...
};
Can all C++ Operators be Overloaded?(2m) No. There are C++ operators that can’t be
overloaded.They include:
•:: -Scope resolution operator
•?: -ternary operator.
•. -member selector
•Sizeof operator
•* -member pointer selector
Different Approaches to Operator Overloading in C++
You can perform operator overloading by implementing any of the following types of functions:
1.Member Function
2.Non-Member Function
3.Friend Function
•The operator overloading function may be a member function when a Left operand is an object of the
Class.
•When the Left operand is different, the Operator overloading function should be a non-member
function.
You can make the operator overloading function a friend function if it needs to access the private and
protected class members.
Rules for Operator Overloading:

Here are rules for Operator Overloading:


•For it to work, at least one operand must be a user-defined class object.
•You can only overload existing operators. You can’t overload new operators.
•Some operators cannot be overloaded using a friend function. However, such operators can be
overloaded using member function.

•You can specify more than one meaning for a C++ operator in one scope.
•This is called operator overloading.
•Operator overloading provides a special meaning of an operator for a user-defined data type.
•You can redefine the majority of C++ operators through operator overloading.
•Not all C++ operators can be overloaded.
•For an operator to be overloaded, at least one of the operands must be a user-defined object.
•Only existing operators can be overloaded. You cannot overload new operators.
Binary Operators and Unary Operators (2m)

The unary operators operate on a single operand and following are the
examples of Unary operators

1. The increment (++) and decrement (--) operators.


2. The unary minus (-) operator.
3. The logical not (!) operator.

The binary operators take two arguments and following are the examples of Binary operators. You
use binary operators very frequently like

1. addition (+) operator,


2. subtraction (-) operator and
3. division (/) operator.
Example 1 Operator Overloading in binary operators (Complex Number )(16m)

* use binary (+) operator to add two complex numbers. */


#include <iostream> Complex_num operator - (Complex_num obj)
using namespace std; {
class Complex_num Complex_num A; // create an object
{ A.x = x - obj.x; // assign values to object
int x, y; // declare data member or variables A.y = y - obj.y;
public: return (A);
void inp() // create a member function to take input }
{ void print() // display the result of addition
cout << " Input two complex number: " << endl; {
cin >> x >> y; cout << x << " + " << y << "i" << "\n";
} }
Complex_num operator + (Complex_num obj) // use bina
ry '+' operator to overload void print2() // display the result of subtraction
{ {
Complex_num A; // create an object cout << x << " - " << y << "i" << "\n";
A.x = x + obj.x; // assign values to object }
A.y = y + obj.y; };
return (A);
} ***Mainfunction in next slide
int main ()
{
Complex_num x1, y1, sum, sub; // here we created object of class Addition i.e x
1 and y1
x1.inp(); // accepting the values
y1.inp();
sum = x1 + y1; // add the objects
sub = x1 - y1; // subtract the complex number
cout << "\n Entered values are: \n"; // display user entered values
cout << " \t";
x1.print();
cout << " \t";
y1.print();
cout << "\n The addition of two complex (real and imaginary) numbers: ";
sum.print(); // call print function to display the result of addition
cout << "\n The subtraction of two complex (real and imaginary) numbers: ";

sub.print2(); // call print2 function to display the result of subtraction


return 0;
}
Example 2 Operator Overloading in Unary Operators (8m)
Decrement Operator Increment Operator
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class OperatorOverload {
class TestClass {
private:
private:
int x;
int count; public:
public: OperatorOverload() : x(10) {}
TestClass() : count(5) {} void operator ++() {
void operator --() { x = x + 2;
count = count - 3; }
} void Print() {
void Display() { cout << "The Count is: " << x;
}
};
cout << "Count: " << count; }
int main() {
}; OperatorOverload ov;
int main() { ++ov;
TestClass tc; ov.Print();
--tc; return 0;
tc.Display(); }
return 0;
}
Example 3 Operator Overloading
// overloading the binary '+' operator to add number
#include <iostream> Arith_num operator + (Arith_num &ob)
using namespace std; {
class Arith_num Arith_num A; // create an object
{ A.x = x + ob.x; // assign values to object
// declare data member or variable return (A);
int x, y; }
public: void print() // display the result of binary + operator
// create a member function to take input {
void input() cout << "The sum of two numbers is: " <<x;
{ }
cout << " Enter the first number: "; };
cin >> x; int main ()
} {
void input2() { Arith_num x1, y1, res; x1.input();
cout << " Enter the second number: "; y1.input();
cin >> y; res = x1 + y1;
} res.print();
return 0;
}

You might also like