0% found this document useful (1 vote)
197 views

Oop Pop

Here is the program for unary operator overloading: #include <iostream> using namespace std; class Number { private: int a; public: void getvalue() { cout<<"Enter the number: "; cin>>a; } void operator++() //overload unary + operator { a++; } void display() { cout<<"Number after increment: "<<a<<endl; } }; int main() { Number n; n.getvalue(); ++n; //call overloaded operator n.display(); return 0; } When this code is compiled and executed

Uploaded by

Dhruv Pandit
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 (1 vote)
197 views

Oop Pop

Here is the program for unary operator overloading: #include <iostream> using namespace std; class Number { private: int a; public: void getvalue() { cout<<"Enter the number: "; cin>>a; } void operator++() //overload unary + operator { a++; } void display() { cout<<"Number after increment: "<<a<<endl; } }; int main() { Number n; n.getvalue(); ++n; //call overloaded operator n.display(); return 0; } When this code is compiled and executed

Uploaded by

Dhruv Pandit
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/ 26

OOP POP

It stands for Object Orientated It stands for Procedural


Abbreviations
Programming. Orientated Programming.

The main program is divided into The main program is divided into
Programs small object depending on the small parts depending on the
problem. functions.

The different parts of the program


The functions of the objects are
are connected with each other by
Linking linked with other objects by using
parameter passing and using the
the message passing.
operating system.

The data and functions of each


Every function contains different
Data individual object act like a single
data.
unit.

Data gets more importance than Functions or algorithms get more


Importance
functions in program. importance than data in program.

Most of the functions use global


Data control Each object controls its own data.
data.

Data does not possibly transfer Same data may be transferable


Transfer
from one object to another. from one function to another.

Data hiding is possible, which


There is no perfect way for data
Data hiding prevents illegal access of the
hiding.
function from outside of it.

Functions communicate with other


One object links with the other
Communication functions maintaining as usual
using the message passing.
rules.
More data or functions can be More data or functions cannot be
added with the program if added with the program if
Addition
necessary. For this purpose, the necessary. For this purpose, the
full program need not be changed. full program needs to be change.

Message passing ensures the To add new data in program, the


Permission permission of accessing member of user should ensure that the
an object from another object. function allows it.

Bottom up process is followed for Top down process is followed for


Process
program design. program design.

Overloading is possible in the form


Overloading of Function Overloading and Overloading is not possible.
Operator Overloading.

Public, private, and protected


Access No access specifiers are used.
access specifiers are used.

Examples C++, Java. Pascal, Fortran

OR

Object Oriented Programming


Procedure Oriented
Programming
Divided Into In POP, program is divided into small parts In OOP, program is divided into parts
called functions. called objects.
Importance In POP,Importance is not given to data but to In OOP, Importance is given to the data rathe
functions as well as sequence of actions to be than procedures or functions because it work
done. a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access Specifiers POP does not have any access specifier. OOP has access specifiers named Public, Priva
Protected, etc.
Data Moving In POP, Data can move freely from function to In OOP, objects can move and communicate w
function in the system. each other through member functions.
Expansion To add new data and function in POP is not so OOP provides an easy way to add new data an
easy. function.
Data Access In POP, Most function uses Global data for In OOP, data can not move easily from functio
sharing that can be accessed freely from function,it can be kept public or private so we
function to function in the system. control the access of data.
Data Hiding POP does not have any proper way for hiding OOP provides Data Hiding so provides more
data so it is less secure. security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator Overload
Examples Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, C#.N

2. Describe Pillars of OOP

1. Abstraction
Abstraction is a process of exposing essential features of an entity by hiding the other irrelevant details.
Abstraction mainly reduces complexity and increases efficiency. An entity can have multiple
abstractions.

2. Encapsulation
Encapsulation is the process of putting data and the operations (functions) that can be performed on
that data into a single container called class. Now, any programmer can use this class without knowing
how it is implemented. Due to encapsulation, data is insulated, thus not directly accessible from the
outside world. This is known as Data Hiding.

Remember, Encapsulation is not data hiding, but, Encapsulation leads to data hiding.

3. Inheritance
In a nutshell, inheritance is a process of creating new class from the existing one. The new class may
have some additional properties and functionalitiy.

4. Polymorphism
Poly means many and Morphs means forms. Polymorphism refers to the ability to take multiple forms
and it allows us to invoke derived class methods through a base class reference during run-time.
3. Difference/Characteristc of Constructor and Destructor(with example)

Example of constructor:

class A
{
int x;
public:
A(); //Constructor
};
Constructors can be defined either inside the class definition or outside class definition using class name
and scope resolution :: operator.
class A
{
int i;
public:
A(); //Constructor declared
};

A::A() // Constructor definition


{
i=1;
}

Example:

class A
{
public:
~A();
};

4. What is Inherictance . Describe types of Inheritance


Inheritance:
In a nutshell, inheritance is a process of creating new class from the existing one. The new class may
have some additional properties and functionalitiy.

Various Types of Inheritance those are provided by C++ are as followings:


1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
In Inheritance Upper Class whose code we are actually inheriting is known as the Base or Super Class
and Class which uses the Code are known as Derived or Sub Class.
1) In Single Inheritance there is only one Super Class and Only one Sub Class Means they have one to
one Communication between them

2) In Multilevel Inheritance a Derived class can also inherited by another class Means in this Whena
Derived Class again will be inherited by another Class then it creates a Multiple Levels.

3) Multiple Inheritances is that in which a Class inherits the features from two Base Classes When a
Derived Class takes Features from two Base Classes.
4) Hierarchical Inheritance is that in which a Base Class has Many Sub Classes or When a Base Class is
used or inherited by many Sub
Classes.

5) Hybrid Inheritance: - This is a Mixture of two or More Inheritance and in this Inheritance a Code
May Contains two or Three types of inheritance in Single Code.
5. Write a program for unary operator overloading.
ALGORITHM:(for understanding)

Step 1: Start the program.


Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator ++ to increment the values
Step 6: Define the function operator - -to decrement the values.
Step 7: Define the display function.
Step 8: Declare the class object.
Step 9: Call the function getvalue
Step 10: Call the function operator ++() by incrementing the class object and call the function display.
Step 11: Call the function operator - -() by decrementing the class object and call the function display.
Step 12: Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>

class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}

void operator++()
{
a=++a;
b=++b;
}

void operator--()
{
a=--a;
b=--b;
}

void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};

void main()
{
clrscr();
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Number\n";
obj.display();
obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}

Output:
Enter the two numbers: 3 6
Increment Complex Number
4+ 7i
Decrement Complex Number
3+ 6i

6. What is Inline funtion? Write a program for inline function


Inline function is a function which when invoked requests the compiler to replace the calling statement
with its body. A keyword inline is added before the function name to make it inline. It is an optimization
technique used by the compilers as it saves time in switching between the functions otherwise. Member
functions of a class are inline by default even if the keyword inline is not used.

Syntax of Inline Function


inline return_type function_name ([argument list])

body of function
}

Program:

#include <iostream>

#include <conio.h>

using namespace std;

inline void print(int x)

cout<<x<< " ";

int main()

int i, N;

cout<<"C++ Program to print first N natural numbers"<<endl<<endl;

cout<<"Enter total number of natural numbers:"<<endl;

cin>>N;

for(i=1;i<=N;i++)

print(i);
}

getch();

return 0;

Output
C++ Program to print first N natural numbers

Enter total number of natural numbers:

10

1 2 3 4 5 6 7 8 9 10

7. What is Function overloading? write a sample program.


Function overloading in C++: C++ program for function overloading. Function overloading means two or
more functions can have the same name but either the number of arguments or the data type of
arguments has to be different. Return type has no role because function will return a value when it is
called and at compile time compiler will not be able to determine which function to call. In the first
example in our code we make two functions one for adding two integers and other for adding two floats
but they have same name and in the second program we make two functions with identical names but
pass them different number of arguments. Function overloading is also known as compile time
polymorphism.

C++ programming code for function overloading


#include <iostream>

using namespace std;

/* Number of arguments are different */

void display(char []); // print the string passed as argument


void display(char [], char []);

int main()
{
char first[] = "C programming";
char second[] = "C++ programming";

display(first);
display(first, second);

return 0;
}

void display(char s[])


{
cout << s << endl;
}

void display(char s[], char t[])


{
cout << s << endl << t << endl;
}

Output of program:

C programming
C programming
C++ programming

8. Explain Cstring methods.

9. Explain C++ Manipulators with example.


Manipulators are functions that are used to format or modify the output stream in various ways.
They have a special characteristic that they are used along with insertion (<<) operator to change the
format of the data.

1. endl
The endl manipulator works the same way as the \n character in C++. That is the endl manipulator
outputs the subsequent data or text in the next line.
But the difference is that endl also flushes the output buffer when it is used in a program.

Here is a sample program that shows how endl works.

<#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num;
cout<<"Enter your roll number: ";
cin>>num;

cout<<"Hello roll number "<<num<<endl;


cout<<"Welcome to your new class!!";
getch();
return 0;
}

setw manipulator:

This manipulator is used to set the width of the output in a program. It takes up an argument n
which is the width of the field in which the output is to be displayed.

By default, the output in the field is right-aligned.

Example:

#include<iostream>

#include<conio.h>

#include<iomanip>

using namespace std;

int main()

int num1,num2,num3;
cout<<"Enter three numbers:\n";

cin>>num1>>num2>>num3;

cout<<"\nDisplaying the three numbers\n"

<<"Num1:"<<setw(8)<<num1<<endl

<<"Num2:"<<setw(8)<<num2<<endl

<<"Num3:"<<setw(8)<<num3<<endl;

getch();

return 0;

Output:

Set fill character

Sets c as the stream's fill character.

Behaves as if member fill were called with c as argument on the stream on which it is inserted as a
manipulator (it can be inserted on output streams).

// setfill example
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setfill, std::setw

int main () {
std::cout << std::setfill ('x') << std::setw (10);
std::cout << 77 << std::endl;
return 0;
}

Output:

xxxxxxxx77

Set decimal precision

Sets the decimal precision to be used to format floating-point values on output operations.

Behaves as if member precision were called with n as argument on the stream on which it is
inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).

// setprecision example Edit & Run


#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision

int main () {
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
return 0;
}

Output:

3.1416
3.14159
3.14159
3.141590000
10. Define Operator overloading with a sample program.

Operator Overloading
Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator
is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on
user-defined data type. For example '+' operator can be overloaded to perform addition on various data
types, like for Integer, String(concatenation) etc.

Algorithm:(only for understanding)

Step 1: Start the program.

Step 2: Declare the class.

Step 3: Declare the variables and its member function.

Step 4: Using the function getvalue() to get the two numbers.

Step 5: Define the function operator +() to add two complex numbers.

Step 6: Define the function operator ()to subtract two complex numbers.

Step 7: Define the display function.

Step 8: Declare the class objects obj1,obj2 and result.

Step 9: Call the function getvalue using obj1 and obj2

Step 10: Calculate the value for the object result by calling the function operator + and operator -.

Step 11: Call the display function using obj1 and obj2 and result.

Step 12: Return the values.

Step 13: Stop the program.

PROGRAM:
#include<iostream.h>

#include<conio.h>

class complex
{

int a,b;

public:

void getvalue()

cout<<"Enter the value of Complex Numbers a,b:";

cin>>a>>b;

complex operator+(complex ob)

complex t;

t.a=a+ob.a;

t.b=b+ob.b;

return(t);

complex operator-(complex ob)

complex t;

t.a=a-ob.a;

t.b=b-ob.b;

return(t);

void display()

cout<<a<<"+"<<b<<"i"<<"\n";
}

};

void main()

clrscr();

complex obj1,obj2,result,result1;

obj1.getvalue();

obj2.getvalue();

result = obj1+obj2;

result1=obj1-obj2;

cout<<"Input Values:\n";

obj1.display();

obj2.display();

cout<<"Result:";

result.display();

result1.display();

getch();

Output:
Enter the value of Complex Numbers a, b
4 5

Enter the value of Complex Numbers a, b

2 2

Input Values

4 + 5i

2 + 2i

Result

6 + 7i

2 + 3i

11. Define Pointer. Explain This pointer , Null pointer , Void pointer with examples.

Pointer is a variable whose value is the address of another variable. Like any variable or constant, you
must declare a pointer before you can work with it. The general form of a pointer variable declaration
is:

type *var-name;

Null Pointer:

It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have
exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned
NULL is called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard libraries, including
iostream. Consider the following program:

#include <iostream>
using namespace std;

int main () {
int *ptr = NULL;

cout << "The value of ptr is " << ptr ;

return 0;
}

When the above code is compiled and executed, it produces the following result:

The value of ptr is 0

This pointer:
The this pointer is passed as a hidden argument to all nonstatic member function calls and is available
as a local variable within the body of all nonstatic functions. this pointer is a constant pointer that
holds the memory address of the current object. this pointer is not available in static member functions
as static member functions can be called without any object (with class name).

Following are the situations where this pointer is used:


1) When local variables name is same as members name
#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

Output:

x = 20

Void Pointer:
Void pointer or generic pointer is a special type of pointer that can be pointed at objects of any data
type. A void pointer is declared like a normal pointer, using the void keyword as the pointers type.

#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int *)ptr);
return 0;
}

12. Define Binary operator overloading . Write a program for Binary operator
overloading.

13. Write a program for bubble sort program ( with pointers/ without pointers)

With ponters:

#include<stdio.h>
#include<stdlib.h>
int bubblesort(int *,int);
int bubblesort(int *arr,int n)
{
int i,j,temp;
for(i=0;i<(n-1);i++)
for(j=0;j<(n-1-i);j++)
{
if(*(arr+j)>*(arr+(j+1)))
{
temp=*(arr+j);
*(arr+j)=*(arr+(j+1));
*(arr+(j+1))=temp;
}
}
return 0;
}

int main()
{
int *arr,i,n;
printf("Enter no. of terms\n");
scanf("%d",&n);
arr=(int *)malloc(n*sizeof(int));
printf("Enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",(arr+i));
bubblesort(arr,n);
printf("Sorted elements are\n");
for(i=0;i<n;i++)
printf("%d\n",*(arr+i));
return 0;
}

Without pointers:

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, arr[50], j, temp;
cout<<"Enter total number of elements :";
cin>>n;
cout<<"Enter "<<n<<" numbers :";
for(i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Sorting array using bubble sort technique...\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
cout<<"Elements sorted successfully..!!\n";
cout<<"Sorted list in ascending order :\n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
getch();
}

Output will be same for both:

14. What is friend class / What is friend function? Write a program using friend
fuction.

A friend function of a class is defined outside that class' scope but it has the right to access all private
and protected members of the class. Even though the prototypes for friend functions appear in the
class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template, in
which case the entire class and all of its members are friends.

Program:

//friend function
#include<iostream.h>

class cls2; //this is forward declaration of class cls2

class cls1{
int a; //this a is for objects of class cls1
public:
void set_a(){
a=4; //setting a for objects of class cls1
}
friend void sum(cls1, cls2);
};

class cls2{
int a; //this a is for objects of class cls2
public:
void set_a(){
a=4; //setting a for objects of class cls2
}
friend void sum(cls1, cls2);
};

void sum(cls1 x, cls2 y){


cout<<x.a+y.a; /*printing the summation of the value of a
*under the object ob1 of class cls1 and
*the value of a under the object
*ob2 of class cls2
*/
}

void main(){
cls1 ob1;
cls2 ob2;

ob1.set_a(); //calling the set_a() function of class cls1 by ob1


ob2.set_a(); //calling the set_a() function of class cls2 by ob2
sum(ob1, ob2); /*calling the friend function sum(cls1, cls2) which
*is common in both the classes cls1 and cls2 and
*thats why it can operate on the variables of
*both the classes.
*/
}

Output: 8

15. Define function templates with syntax.

Templates are the foundation of generic programming, which involves writing code in a way that is
independent of any particular type.

A template is a blueprint or formula for creating a generic class or a function. The library containers like
iterators and algorithms are examples of generic programming and have been developed using
template concept.

There is a single definition of each container, such as vector, but we can define many different kinds of
vectors for example, vector <int> or vector <string>.

The general form of a template function definition is shown here:

template <class type> ret-type func-name(parameter list) {


// body of function
}

Here, type is a placeholder name for a data type used by the function. This name can be used within
the function definition.

16. Explain Exception handling Mechanism.

An exception is a problem that arises during the execution of a program. A C++ exception is a response
to an exceptional circumstance that arises while a program is running, such as an attempt to divide by
zero.

Exceptions provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keywords: try, catch, and throw.

throw: A program throws an exception when a problem shows up. This is done using
a throw keyword.
catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.

try: A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:

try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}

There should be multiple catch statements to catch different type of exceptions in case your try block
raises more than one exception in different situations.

You might also like