OOPS

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

UN IT 1 :- OBJECT ORIENTED PROGRAMMING

QUES:- DEFINE ADVANTAGES AND DISADVANTEGES OF


STRUCTURED PROGRAMMING?
ANS:-
Advantages of Structured Programming

a) Complexity can be reduced using the concepts of divide


and conquer.
b) Logical structures ensure clear flow of control.
c) Increase in productivity by allowing multiple programmers
to work on different parts of the project independently at the
same time.
d) Modules can be re-used many times, thus it saves time,
reduces complexity, and increases reliability.
e) Easier to update/fix the program by replacing individual
modules rather than larger amounts of code.
f) Ability to either eliminate or at least reduce the necessity
of employing GOTO statement
[8:35 am, 21/9/2024] Kritika M: Disadvantages of Structured
Programming
a) Since GOTO statement is not used, the structure of the
program needs to be planned meticulously.
b) Lack of encapsulation.
c) Same code repetition.
d) Lack of information hiding.
e) Change of even a single data structure in a program
necessitates changes at many places throughout it, and
hence, the changes become very difficult to track even in a
reasonably sized program.
f) Not much reusability of code.
g) Can support the software development projects easily up
to a certain level of complexity. If complexity of the project
goes beyond a limit, it becomes difficult to manage.

QUES:- STRUCTURED Vs OBJECT-ORIENTED PROGRAMMING

ANS:-
The OOP, can be considered to be a type of structured
programming which uses structured programming techniques
for program flow, but adds more structure for data to be
modelled. We have highlighted some of the basic differences
between the two as under:
1) OOP is closer to the phenomena in real world due to the
use of objects whereas structured programming is a bit away
from the natural way of thinking of human beings.

2) Structured programming is a subset of object-oriented


programming. Therefore, OOP can help in developing much
larger and complex programs than structured programming.

3) Under structured programming, the focus of a program is


on procedures or functions (behaviour) and the data is
considered separately (data structures are not well organized
within the program) whereas in OOP, data (structure) and
methods (behaviour) both are in collective focus.

4) In OOP, the basic units of manipulation are the objects


whereas in case of structured programming, functions or
procedures are the basic units of manipulation.
5) The focus of a program is on manipulation of data in
structured programming whereas the focus of OOP is on both
data (structures and states of objects) as well as on its
manipulation (behaviour of objects).

6) In OOP, data is hidden within the objects and its


manipulation can be strictly controlled whereas in structure
programming the data in the form of variables is exposed to
unintended manipulation too.

7) The OOP promotes the reuse of classes and their parts of


the code too. In addition, it also supports the inheritance of
state and behaviour. This feature is missing in structured
programming.

8) The OOP supports polymorphism of operations.

9) The concepts of OOP have got integrated with most of the


prominent object-oriented methodologies of software
development in a better way and help in reducing the
development effort and time as compared
with that of structured methodologies based on structured
programming.

10) The structured programming normally emphasized on


single exit point in their constituent functions or procedures.
Since each function/procedure allocates some memory to
itself for storing the values of its variables and code, before
the exit, there must be a provision for deallocating this
memory. Otherwise, more and more of the memory gets
occupied by each function/procedure and in large programs,
there may occur a shortage of m…shortage of memory for
use by other functions/procedures and the processing can
get slower or even completely halted. When in any
function/procedure, memory is allocated, but not
deallocated, a memory leak is said to have occurred (the
memory has leaked out of the computer) in it.

QUES: Define Message Passing ?


ANS:-

In object oriented languages, you can consider a running


program under execution as a pool of objects where objects
are created for ‘interaction’ and later destroyed when their
job is over. This interaction is based on ‘messages’ which are
sent from one object to another asking the recipient object to
apply one of its own methods on itself and hence, forcing a
change in its state.
The objects are made to communicate or interact with each
other with the help of a mechanism called message passing.
The methods of any object may communicate with each
other by sending and receiving messages in order to change
the state of the object. An Object may communicate with
other objects by sending and receiving messages to and from
their methods in order to change either its own state or the
state of other objects taking part in this communication or
that of both. An object can both send and receive messages
QUES: DEFINE- BENEFITS OF OOP ?
ANS:-

1) As OOP is closer to the real world phenomena, hence, it is


easier to map real world problems onto a solution in OOP.
2) The objects in OOP have the state and behaviour that is
similar to the real world objects.
3) It is more suitable for large projects.
4) The projects executed using OOP techniques are more
reliable.
5) It provides the bases for increased testability (automated
testing) and hence higher quality.
6) Abstraction techniques are used to hide the unnecessary
details and focus is only on the relevant part of the problem
and solution.
7) Encapsulation helps in concentrating the structure as well
as the behaviour of various objects in OOP in a single
enclosure.
8) The enclosure is also used to hide the information and to
allow strictly controlled access to the structure as well as the
behaviour of the objects.
9) OOP divides the problems into collection of objects to
provide services for solving a particular problem.
10) Object oriented systems are easier to upgrade/modify

11) The concepts like inheritance and polymorphism provide


the extensibility of the OOP languages.
12) The concepts of OOP also enhance the reusability of the
code written.
13) Software complexity can be better managed.
14) The use of the concept of message passing for
communication among the objects makes the interface
description with external system much simpler.

QUES:- Differentiate between information hiding and


encapsulation.

ANS:-
The mechanism of information hiding is said to provide a
strictly controlled access to the information enclosed within
the capsule. Encapsulation is the process of enclosing within
classes and objects the attributes and the methods. But
information hiding cannot be treated as encapsulation, it is
different e.g. an array or a record structure also encloses the
information but this information cannot be said to be hidden.
It is true that the encapsulation mechanism like classes and
objects hide information but these also provide visibility of
some of their information through well defined interfaces
QUES:- DEFINE OOPS CONCEPTS ?
ANS:-

Class: A class in C++ is the building block, that leads to Object-


Oriented programming. It is a user-defined data type, which
holds its own data members and member functions, which
can be accessed and used by creating an instance of that
class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many
cars with different names and brand but all of them will share
some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range etc. So here, Car is the class and
wheels, speed limits, mileage are their properties.
• A Class is a user defined data-type which has data
members and member functions.
• Data members are the data variables and member
functions are the functions used to manipulate these
variables and together these data members and member
functions defines the properties and behavior of the objects
in a Class.
• In the above example of class Car, the data member will
be speed limit, mileage etc and member functions can be
apply brakes, increase speed etc.

An Object is an instance of a Class. When a class is defined,


no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.

Encapsulation:- Encapsulation is defined as wrapping up of


data and information under a single unit. In Object-Oriented
Programming, Encapsulation is defined as binding together
the data and the functions that manipulate them.

Consider a real-life example of encapsulation, in a company,


there are different sections like the accounts section, finance
section, sales section etc. The finance section handles all the
financial transactions and keeps records of all the data
related to finance. Similarly, the sales section handles all the
sales-related activities and keeps records of all the sales. Now
there may arise a situation when for some reason an official
from the finance section needs all the data about sales in a
particular month. In this case, he is not allowed to directly
access the data of the sales section. He will first have to
contact some other officer in the sales section and then
request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a
single name “sales section”.
Encapsulation also leads to data abstraction or hiding. As
using encapsulation also hides the data. In the above
example, the data of any of the section like sales, finance or
accounts are hidden from any other section.
ABSTRACTION:-
Data abstraction is one of the most essential and important
features of object-oriented programming in C++. Abstraction
means displaying only essential information and hiding the
details. Data abstraction refers to providing only essential
information about the data to the outside world, hiding the
background details or implementation.
Consider a real-life example of a man driving a car. The man
only knows that pressing the accelerators will increase the
speed of the car or applying brakes will stop the car but he
does not know about how on pressing accelerator the speed
is actually increasing, he does not know about the inner
mechanism of the car or the implementation of accelerator,
brakes etc in the car. This is what abstraction is.
• Abstraction using Classes: We can implement
Abstraction in C++ using classes. The class helps us to group
data members and member functions using available access
specifiers. A Class can decide which data member will be
visible to the outside world and which is not.
• Abstraction in Header files: One more type of
abstraction in C++ can be header files. For example, consider
the pow() method present in math.h header file. Whenever
we need to calculate the power of a number, we simply call
the function pow() present in the math.h header file and pass
the numbers as arguments without knowing the underlying
algorithm according to which the function is actually
calculating the power of numbers.

POLYMORPHISM:-
The word polymorphism means having many forms. In simple
words, we can define polymorphism as the ability of a
message to be displayed in more than one form.
A person at the same time can have different characteristic.
Like a man at the same time is a father, a husband, an
employee. So the same person posses different behaviour in
different situations. This is called polymorphism.
An operation may exhibit different behaviours in different
instances. The behaviour depends upon the types of data
used in the operation.
C++ supports operator overloading and function overloading.
• Operator Overloading: The process of making an
operator to exhibit different behaviours in different instances
is known as operator overloading.
• Function Overloading: Function overloading is using a
single function name to perform different types of tasks.
Polymorphism is extensively used in implementing
inheritance
• Example: Suppose we have to write a function to add
some integers, some times there are 2 integers, some times
there are 3 integers. We can write the Addition Method with
the same name having different Parameters, the concerned
method will be called according to parameters.

INHERITENCE:-

The capability of a class to derive properties and


characteristics from another class is called Inheritance.
Inheritance is one of the most important features of Object-
Oriented Programming.
• Sub Class: The class that inherits properties from
another class is called Sub class or Derived Class.
• Super Class:The class whose properties are inherited by
sub class is called Base Class or Super class.
Reusability: Inheritance supports the concept of “reusability”,
i.e. when we want to create a new class and there is already a
class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we
are reusing the fields and methods of the existing class.

Example: Dog, Cat, Cow can be Derived Class of Animal Base


Class

UNIT 2 INTRODUCTION TO C+ +

QUES:- DIFFERENCE BETWEEN C AND C++


ANS:-

•C++ is regarded as an intermediate-level language. It


comprises a combination of both high-level and low-level
language features. C++ is an extension to C Programming
language. The difference between the two languages can be
summarised as follows:

* The variable declaration in C, must occur at the top of the


function block and it must be declared before any executable
statement. In C++ variables can be declared anywhere in the
program.

* In C++ we can change the scope of a variable by using scope


resolution operator. There is no such facility in C language.

* C Language follows the top-down approach while C++


follows both top-down and bottom-up design approach.

* C is a procedure language and C++ is an object oriented


language.

C allows a maximum of 32 characters in an identifier name


whereas C++ allows no limit on identifier length.

* C++ is an extension to C language and allows declaration of


class, while C language does not allow this feature.

* C++ allows inheritance and polymorphism while C language


does not
QUES:- DEFINE DATA TYPES IN C++ ?
ANS:-

QUES:- DEFINE TYPE CONVERSION ?


ANS:-
C++ allows us to convert data of one type to that of another.
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)

The type conversion that is done automatically done by the


compiler is known as implicit type conversion. This type of
conversion is also known as automatic conversion.
EX. 3 +7.5=10.5

Explicit Conversion
When the user manually changes data from one type to
another, this is known as explicit conversion. This type of
conversion is also known as type casting.

5/2= 2
(float)5/2=2.5

LITERALS OR CONSTANTS

A number which does not charge its value during execution of


a program is known as a constant or literals. Any attempt to
change the value of a constant will result in an error message.
A keyword const is added to the declaration of an identifier to
make that identifier constant. A constant in C++ can be of any
of the basic data types. Let us consider the following C++
expression: const float Pi = 3.1215; The above declaration
means that Pi is a constant of float types having a value
3.1415.
Examples of some valid constant declarations are:
const int rate = 50;
const float Pi = 3.1415;
const char ch = „A‟;

QUES:- DEFINE Escape Sequence


ANS:-
There are some characters which can‟t be typed by keyboard
in C++ programming language. These are called non-graphic
characters. An escape sequence is represented by backslash
(\) followed by one or more characters
\a Bell (beep)
\b Backspace
\f Formatted
\n Newline or line feed
\r Carriage return
\t Horizontal tab
\v Vertical tab
\? Question mark
\ \ Backslash
QUES:- DEFINE OPERATORS IN c++

ANS:-C++ has a rich set of operators. Operators is the term


used to describe the action to be taken between two data
operands. Expressions are made by combining operators
between operands. C++ supports six types of operators:

* Arithmetical operators
* Relational operators
* Logical operators
* Bitwise operators
* Precedence of operators
* Special operators

* Arithmetical operators :-

Operator Meaning Example Answer


+ addition 8+5 13
- subtraction 8-5 3
* multiplication 8*5 40

/ division 10/2 5
% modulo 5%2 1

Relational operators

Operator Meaning Example


== Equal to 5==5
!= Not equal to 5!=7
> Greater than 7>5
< Less than 8<9
>= Greater than or equal to 8>=8
<= Less than or equal to 9<=9
Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Example: !(5 == 5) // evaluates to false because the


expression at its right (5 == 5) is true. !(6 <= 4) // evaluates to
true because (6 <= 4) would be false. !true // evaluates to
false !false // evaluates to true

Bitwise Operators

operator Asm equivalent Description


& AND Bitwise AND
| OR Bitwise Inclusive OR
^ XOR Bitwise Exclusive OR
~ NOT Unary complement (bit inversion)
<< SHL Shift Left
>> SHR Shift Right

Precedence of Operators
a = 5 + 7 % 2 Here we may doubt if it really means:
A = 5 + (7 % 2) // with a result of 6, or a = (5 + 7) % 2 // with a
result of 0
The correct answer is the first of the two expressions, with a
result of 6.
Special Operators
Increment and Decrement Operator
++,--

The size of operator


Example: sizeof (char) returns 1
sizeof (int) returns 2 sizeof (float) returns
if k is integer variable, the sizeof (k) returns 2.

The comma operator


The comma operator gives left to right evaluation of
expressions. It enables to put more than one expression
separated by comma on a single line. Example: int i = 20, j =
25; In the above statements, comma is used as a separator
between the two statements

[8:35 am, 21/9/2024] Kritika M: QUES:- Define class?


Ans:- class is an object template. Every object under that
class has the same data format, definition and responds in
the same manner to an operation. A class is a user defined
data type like any other built-in data type for example int,
char, float, .. etc. It is most important feature of C++. It makes
C++ an Object- Oriented language.
A class has a class name, a set of attributes (data
members/characteristics) and a set of actions or
services(function members/methods).
class Class_name
{
private :
variable declaration;
function declaration;
public :
variable declaration;
function declaration;
protected :
variable declaration;
function declaration;
};
Let us see, how Employee class is defined
class Employee
{
int id;
char name[25];
char deptt[25];
public:
void get_data(void)
{
cout<< “Enter Employee ID:” <<endl;
cin>>id;
cout<<”Enter name:”<<endl;
cin>>name;
cout<< “Enter department:”<<endl;
cin>>deptt;
}
void display_information(void)
{
cout<< “Employee ID=” <<id<<endl;
cout<< “Employee Name=” <<name<<endl;
cout<< “Employee Department=” <<deptt<<endl;
}
};

How to create an object?


void main()
{
Employee e1; // first object/variable of a Employee class
Employee e2; // second object/variable of a Employee class
cout<<"\nEnter 1st Employee Basic Information:"<<endl;
e1.get_data(); // object e1 calls member get_data()
cout<<"\nEnter 2nd Employee Basic Information:"<<endl;
e2.get_data(); // object e2 calls member get_data()
cout<<"\n1st Employee Basic Information:"<<endl;
e1.display_info(); // object e1 calls member display_info()
cout<<"\n 2nd Employee Basic Information:"<<endl;
e2.display_info(); // object e2 calls member display_info()
}

OBJECT:- objects are the basic run-time entities in Object-


Oriented programming language. They occupy space in
memory that keeps its state and is operated on by the
defined operations on the object, while a class defines a
possible set of objects. The relationship between a class and
objects of that class is similar to the relationship between a
type and elements of that type. A class represents a set of
objects that share a common structure and a common
behavior, whereas an object is an instance of a class. In the
next section we will see as to how object is created. The
declaration of a class does not define any object but only
specify the structure of objects i.e. what they will contain. A
class must be instantiated in order to make use of the
services provided by it. This process of creating objects
(variables) of the class is called class instantiation or
instantiating of objects. Thus, an object is an instantiation of
a class. The common syntax of instantiating object of a class /
declaration of a object is as follows: class className
objectName1, objectName2 …; or className objectName1,
objectName2 …; AS ABOBE
EXPLAINED with EXAMPLE

QUES :- Write C++ program to find out the minimum and


maximum of three given integer numbers
ANS:-
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<"\n Minimum value is ="<<min<<endl;
}
};
void Number :: get_data(void)
{
cout<< "\n Enter the value of fist number(x):"<<endl;
cin>>x;
cout<< "\n Enter the value of second number(y):"<<endl;
cin>>y;
cout<< "\n Enter the value of third number(z):"<<endl;
cin>>z;
}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<"\n Maximun value is ="<<max<<endl;
}
void main()
{
Number num;
num.get_data();
num.minimum();
num.maximum();
}
ques:- define passing object as an argument or matix
operation in c++?
ANS:-
Passing Objects as Arguments We can pass objects as
arguments to a function like any other data type. This can be
done by a pass-by-value and a pass-by-reference. In pass-by-
value, a copy of the object is passed to the function and any
modifications made to the object inside the function are not
reflected in the object used to call the function. While, in
pass-by-reference, an address of the object is passed to the
function and any changes made to the object inside the
function is reflected in the actual object. Furthermore, we
can also return object from the function like any other data
type
Objects and Classes Consider the following C++ program for
addition and multiplication of two square matrices which
illustrates the above concepts.
#include<iostream.h>
#define MAX_SIZE 10
int n;
class Matrix
{
int item[MAX_SIZE][MAX_SIZE];
public:
void get_matrix(void);
void display_matrix(void);
Matrix add(Matrix m);// Matrix object as argumentand as
return: pass by value
void mul(Matrix &mat, Matrix m);// Matrix object as
argument: pass by reference and pass by value
};
void Matrix :: get_matrix(void)
{
cout<< "\n Enter the order of square matrix(nXn):"<<endl;
cin>>n;
cout<< "\n Enter the element of matrix:"<<endl;
for (int i=0;i<n; i++)
for (int j=0;j<n; j++)
cin>>item[i][j];
}
void Matrix :: display_matrix(void)
{
cout<<"\n The element of matrix is :"<<endl;
for (int i=0;i<n; i++)
{
for (int j=0;j<n; j++)
cout<<item[i][j]<<"\t";
cout<<endl;
}
}
Matrix Matrix :: add(Matrix m)
{
Matrix temp; // object temp of Matrix class
for (int i=0;i<n; i++)
for (int j=0;j<n; j++)
temp.item[i][j]=item[i][j]+m.item[i][j];
return (temp); // returm matrix object
}
void Matrix :: mul(Matrix &rm, Matrix m)
{
for (int i=0;i<n; i++)
for (int j=0;j<n; j++)
{
rm.item[i][j]=0;
for(int k=0; k<n; k++)
rm.item[i][j]=rm.item[i][j]+item[i][k]*m.item[k][j];
}
}
void main()
{
Matrix X, Y, Result;
cout<<"Matrix X :"<<endl;
X.get_matrix();
cout<<"Matrix Y :"<<endl;
Y.get_matrix();
cout<<"\n Addition of X & Y :"<<endl;
Result=X.add(Y);
Result.display_matrix();
cout<<"\n Multiplication of X & Y :"<<endl;
X.mul(Result,Y); //result=X*Y
Result.display_matrix();
}
ques:- Define encapsulation?
Ans:- encapsulation is a process of wrapping similar code in
one place. In C++, we can bundle data members and
functions that operate together inside a single class.
For example,
class Rectangle
{ public:
int length;
int breadth;
int getArea()
{ return length * breadth;
}
};
In the above program, the function getArea() calculates the
area of a rectangle. To calculate the area, it needs length and
breadth.
Hence, the data members (length and breadth) and the
function getArea() are kept together in the Rectangle class.
Ques:- Define data abstraction?

Ans:- Abstraction is one of the feature of Object Oriented


Programming, where you show only relevant details to the
user and hide irrelevant details. For example, when you send
an email to someone you just click send and you get the
success message, what actually happens when you click send,
how data is transmitted over network to the recipient is
hidden from you (because it is irrelevant to you).

the core principle of implementing abstraction in C++ is


permission labels that determine how the data is accessed in
a program. To impose restrictions on data members of a class,
we can use permission labels as follows:
• Public - Data members and member functions declared
as public can be accessed from anywhere the class is visible.
• Private - Data members and member functions declared
as private can only be accessed within the class. Outside of
the class, they are inaccessible.
• Protected – Data members and member functions can
be accessed by their friend class and derived class only.
Using the aspects above given by permission labels, we can
implement abstraction. Say, in a class, the members who
determine the internal implementation can be classified as
private.
And it is possible to mark the essential details necessary to be
provided to the outside world as public. These public
members have access to the private members since they are
members of the class.
Program to illustrate abstraction using permission labels:
#include <iostream>
using namespace std;

class abstraction
{
private:
int x, y;

public:

// method to set values of


// private members
void set(int m, int n)
{
x = m;
y = n;
}

void display()
{
cout<<"x = " <<x << endl;
cout<<"y = " << y << endl;
}
};

int main()
{
abstraction sp;
sp.set(20, 30);
sp.display();
return 0;
}
Output:
Sum = 95
In the program above, you can see that we are not allowed to
directly access the variables x and y. But you can call the set()
function to set the values x and y. The display() function is
called to display the values x and y.
Advantages of data abstraction
• It prevents the user from writing low-level code.
• It prevents duplication of software and increases
reusability.
• The internal class implementation can be altered
without impacting the user.
• It helps to improve the privacy of an application or
program as the user is only presented with relevant
information.

QUES:- Define friend Function?


Ans:- A friend function in C++ is defined as a function that can
access private, protected and public members of a class. The
friend function is declared using the friend keyword inside
the body of the class
• Even though the prototypes for friend functions appear
in the class definition, friends are not members functions.
• We can declare friend functions anywhere in a class
definition, that is either in public, private or protected
sections.
• We can do friend declarations anywhere in a class
definition, i.e. either in public, private or protected sections.
• Violates the data hiding principle of classes, so we
should avoid it as much as possible.
• You can grant friendship but not take it, i.e., for class B
to be a friend of class A, class A must explicitly declare that
class B is its friend.
• The friendship relation is neither symmetric nor
transitive.
Friend relationship cannot be inherited.
Benefits of friend function
• A friend function is used to access the non-public
members of a class.
• It allows to generate more efficient code.
• It provides additional functionality which is not normally
used by the class.
• It allows to share private class information by a non
member function

Characteristics:-
• 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.

example
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }
Output:
Length of box: 10
Ques:- Define static member?
Ans:- static members are data members (variables) or
methods that belong to a static or a non static class itself,
rather than to objects of the class. Static members always
remain the same, regardless of where and how they are used.
Because static members are associated with the class, it is
not necessary to create an instance of that class to invoke
them.
Since a static variable is associated with the class, only one
copy of the variable exists in memory. This copy is shared by
all objects of that class.
Some of the features of static members are as follows:
• A static member has access to all static members of its
containing class, including private members.
• A static member can be declared using access control
modifiers.
• A static member class can use any other static member
without qualifying its name with the name of the containing
class.
Properties of static member functions:
1. A static function can only access other static variables or
functions present in the same class
2. Static member functions are called using the class name.
Syntax- class_name::function_name( )
example
#include <iostream>

using namespace std;

class Example{
static int Number;
int n;

public:

void set_n(){

n = ++Number;
}

void show_n(){

cout<<"value of n = "<<n<<endl;
}

static void show_Number(){

cout<<"value of Number = "<<Number<<endl;


}
};

int Example:: Number;

int main()
{
Example example1, example2;

example1.set_n();
example2.set_n();

example1.show_n();
example2.show_n();

Example::show_Number();

return 0;
}
Output:

From the above output, we can see that the value of the
variable ‘n’ is different for both the objects ‘example1’ and
‘example2’ of the class ‘Example’. Since the variable ‘Number’
is a class variable its value is the same for both the objects
‘example1’ and ‘example2’. Static member variables and
functions are used when common values are to be shared
across all the objects. While programming, the use of static
keyword should be done wisely.

UNIT 4 :-CONSTRUCTORS AND DESTRUCTORS


QUES:- DEFINE CONSTRUCTOR?
C++ is an object oriented programming (OOP) language which
provides a special member function called constructor for
initializing an object when it is created. This is known as
automatic initialization of objects.

•They should be declared in the public section.


* They are invoked directly when an object is created.
* They don’t have return type, not even void and hence can’t
return any values.
* They can’t be inherited; through a derived class, can call the
base class constructor.
* Like other C++ functions, they can have default arguments.
* Constructors can’t be virtual.
* Constructor can be inside the class definition or outside the
class definition.
* Constructor can’t be friend function.
* They can’t be used in union.
* They make implicit calls to the operators new and delete
when memory allocation is required.
When a constructor is declared for a class, initialization of the
class objects becomes necessary after declaring the
constructor
C++ constructors have the following limitations:

* No return type A constructor cannot return a result, which


means that we cannot signal an error, during the object
initialization. The only way of doing it is to throw an exception
from a constructor.
* Naming A constructor should have the same name as the
class, which means we cannot have two constructors that
both take a single argument.

* Compile time bound At the time when we create an object,


we must specify the name of a concrete class which is known
at compile time. There is no way of dynamic binding
constructors at run time.

* There is no virtual constructor We cannot declare a virtual


constructor. We should specify the exact type of the object at
compile time, so that the compiler can allocate memory for
that specific type. If we are constructing derived object, the
compiler calls the base class constructor first and the derived
class hasn't been initialized yet. This is the reason why we
cannot call virtual methods from the constructor

EXAMPLE FOR CNSTRUCTOR

# include<iostream.h>
# include<conio.h>
class student
{
public:
student() // user defined constructor
{
cout<< “object is initialized”<<end1;
}
};
void main ()
{
student x,y,z;
getch();
}

QUES: DEFINE COPY CONSTRUCTOR? WITH AN EXAMPLE?


ANS:- A copy constructor is used to declare and initialize an
object from another objectThus the process of initializing
through a copy constructor is known as copy initialization. A
copy constructor is always used when the compiler has to
create a temporary object of a class object. The copy
constructors are used in the following situations
* The initialization of an object by another object of the same
class.
* Return of objects as a function value.
* Stating the object as by value parameters of a funct

EXAMPLE OF COPY CONSRRUCTOR


#include<iostream>
#include<conio.h>
using namespace std;
class student
{
int roll;
char name[30];
public:
student() // default constructor
{
roll =10;
strcpy(name,"x");
}
student( student &O) // copy constrcutor
{
roll =O.roll;
strcpy(name, O.name);
}
void input_data()
{
cout<<"\n Enter roll no :"; cin>>roll;
cout<<"\n Enter name :"; cin>>name;
}
void show_data()
{
cout<<"\n Roll no :"<<roll;
cout<<"\n Name :"<<name;
}
};

int main()
{
student s; // default construtor
s.show_data();
student A(s); // copy constructor
A.show_data();
getch();
return 0;
}
QUES: DEFINE CONSTRUCTOTR OVERLOADING?
ANS:-
Constructor Overloading When more than one constructor
function is defined in a class, then it is called constructor
overloading or use of multiple constructor in a class. It is used
to increase the flexibility of a class by having more number of
constructors for a single class. Overloading constructors in C+
+ programming gives us more than one way to initialize
objects in a class.

#include<iostream>
#include<conio.h>
using namespace std;
class student
{
int roll;
char name[30];
public:
student(int x, char y[]) // parameterized constructor
{
roll =x;
strcpy(name,y);
}
student() // normal constructor
{
roll =100;
strcpy(name,"y");
}

void input_data()
{
cout<<"\n Enter roll no :"; cin>>roll;
cout<<"\n Enter name :"; cin>>name;
}
void show_data()
{
cout<<"\n Roll no :"<<roll;
cout<<"\n Name :"<<name;
}
};

int main()
{
student s(10,"z");
s.show_data();
getch();
return 0;
}

The above C++ program is used to create a constructor


student inside the class student. Here in this program, the
student constructor has been defined in many ways and the
output of the program is student name and his roll no
QUES:- DEFINE DESTRUCTOR WITH AN EXAMPLE?
ANS:-
A destructor, as the name implies, is used to destroy the
objects that have been created by using constructor. They de-
initialize objects when they are destroyed. A destructor is
invoked when an object of the class goes out of scope, or
when the memory occupied by it is de allocated using the
delete operator. A destructor is a function that has the same
name as that of the class but is prefixed with a ~ (tilde).
Destructor takes no arguments or specifies a return value, or
explicitly returns a value not even void. It is called
automatically by the compiler when an object is destroyed. A
destructor cleans up the memory that is no longer required
or accessible
#include<iostream.h>
#include<conio.h>
class student // student is a class
{ public : ~student() // destructor declaration
{ cout <<"Thanx for using this program" <<endl;
}
void main()
{ clrscr();
student s1; // s1 is an object
getch();
}

The main application and characteristics of destructors are


given as follows:
1. Destructor functions are invoked automatically when the
objects are destroyed.
2. We can have only one destructor for a class, i.e.
destructors can’t be overloaded.
3. If a class have destructor, each object of that class will be
de initialized before the object goes out of the scope
4. Destructor function, also obey the usual access rules of as
other member function do.
5. No argument can be provided to a destructor, neither does
it return any value.
6. Destructor can’t be inherited.
7. A destructor may not be static.
8. It is not possible to take the address of destructor.
9. Member function may be called from within a destructor.
10. An object of a class with a destructor can’t be a member
of a union.
11. We may make an object const if it does not change any of
its data value.

Limitations of destructors: C++ destructors have mainly two


disadvantages:
1) They are case sensitive.
2) They are no good for big programs having thousand lines
of code

QUES:-DEFINE MEMORY MANAGEMENT FUNCTIONS?


ANS:-
C++ offers a wide range of choices for the management of
memory. There are various techniques to manage the
memory in object oriented programming such as C++. Some
of the techniques for memory management are given as
follows:
All programming languages use manual techniques to
determine when to allocate a new object from the free store.
C++ language uses the new operator to determine when an
object ought to be created and memory is allocated to it.
There are two types of memory management operators in C+
+. These are:
* new
* delete

These two memory management operators are used for


allocating and freeing memory blocks in efficient and
convenient way. The fundamental issue is the determination
of when an object is no longer needed (i.e. is garbage), and
arranging for its underlying storage to be returned to the free
store so that it may be re-used to satisfy future memory
requests. Constructors and destructor are used in C++
programming language to initialize and destroy the memory
blocks, when it is no longer required by the program. In
manual memory allocation, this is also specified manually by
the programmer; at the time of writing the codes by
programmer.

QUES:- DEFINE MEMBER FUNCTIONS?


ANS:-
A member function performs an operation required by the
class. It is the actual interface to initiate an action of an
object belonging to a class. It may be used to read,
manipulate, or display the data member. The data member of
a class must be declared within the body of the class, while
the member functions of a class can be defined in two places:
(i) inside the class definition
(ii) (ii) outside the class definition
iii) The syntax of a member function definition changes
depending on whether it is defined inside or outside the class
declaration/definition. However, irrespective of the location
of their definition, the member function must perform the
same operation. Thus, the code inside the function body
would be identical in both the cases. The compiler treats
these two definitions in a different manner. Let us see, how
we can define the member function inside the class
definition. The syntax for specifying a member function
declaration is similar to a normal function definition except
that is enclosed within the body of a class. Foe example, we
could define the class as follows:
• Write a C+ + program to find out the sum of n numbers ?
#include<iostream.h>
#define MAX_SIZE 25
class Sum
{
int number[MAX_SIZE];
int n;
int total;
public:
void get_data(void)
{
int i;
cout<<"Enter Total Number :"<<endl;
cin>>n;
cout<<"Enter Number One by One:"<<endl;
for(i=0; i<n; i++)
{
cout<<"Enter Number"<<i+1<<":"<<endl;
cin>>number[i];
}
}
void cal_sum(void)
{
total=0;
int i;
for (i=0; i<n; i++)
total=total+number[i];
}
void display_sum(void)
{
cout<<"\nSum :"<<total<<endl;
}
};
void main()
{
Sum s;
s.get_data();
s.cal_sum();
s.display_sum();
}

What do you mean by default constructor? Explain by taking


example.
ANS:-
A default constructor is a constructor that either has no
parameters, or if it has parameters, all the parameters have
default values. Following program depicts the use of default
constructor in C++ programming
Default constructors do not take any parameters. If a default
constructor is not provided by the programmer explicitly,
then the compiler provides a implicit default constructor. In
that case, the default values of the variables are 0.
A program that demonstrates default constructors is given as
follows.
Example

#include <iostream>
using namespace std;
class DemoDC {
private:
int num1, num2 ;
public:
DemoDC() {
num1 = 10;
num2 = 20;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main() {
DemoDC obj;
obj.display();
return 0;
}
Output
num1 = 10
num2 = 20

Define parameterized constructor by taking a C++ program


ANS:-
We can write a constructor in C++ which can accept
parameters for its invocation. Such constructor that can take
the arguments are called parameterized constructor
#include <iostream>
using namespace std;
// declaring a class
class rectangle {
private:
double length;
double breadth;
public:
// creating parameterized constructor
rectangle(double len, double brt) {
// initialize private variables
length = len;
breadth = brt;
}
double calculateArea() {
return length * breadth;
}
};
int main() {
// creating objects and initializing data members
rectangle rect1(10, 8.6);
rectangle rect2(8.5, 6);
cout << “Area of rectangle 1: ” << rect1.calculateArea() <<
endl;
cout << “Area of rectangle 2: ” << rect2.calculateArea() <<
endl;
return 0;
}
What do you mean by constructor overloading in C ++.
Explain by taking one example.
ANS:-
When more than one constructor function is defined in a
class, then it is called constructor overloading or use of
multiple constructor in a class. It is used to increase the
flexibility of a class by having more number of constructors
for a single class. Overloading constructors in C++
programming gives us more than one way to initialize objects
in a class.

// C++ program to demonstrate constructor overloading


#include <iostream>
using namespace std;

class Person {
private:
int age;

public:
// 1. Constructor with no arguments
Person() {
age = 20;
}

// 2. Constructor with an argument


Person(int a) {
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;
}
Output
Person1 Age = 20
Person2 Age = 45
QUES:- EXPLAIN WITH EXAMOPLE CONTINUE,BREAK,EXIT
GOTO STMTS
ANS:-
In C++, the break statement terminates the loop when it is
encountered.
The syntax of the break statement is:
break;
example
// program to print the value of i

#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}

return 0;
}
output
1
2
continue stmt:-
n computer programming, the continue statement is used to
skip the current iteration of the loop and the control of the
program goes to the next iteration.
The syntax of the continue statement is:
continue;

// program to print the value of i

#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}

cout << i << endl;


}

return 0;
}
Output
1
2
4
5

exit stmt

The exit function, declared in <stdlib. h>, terminates a C++


program. The value supplied as an argument to exit is
returned to the operating system as the program's return
code or exit code. By convention, a return code of zero means
that the program completed successfully

o find whether a given number is prime or not using


do ..while loop.
#include<iostream.h>
#include<math.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int n;
int q;
clrscr();
cout<<"Enter the Number : ";
cin>>n;
int i=2;
do
{
if(n%i==0)
goto II;
i++;
}
while(i<=int( sqrt(n)));
cout<<n<<" is a prime number ";
exit(1);
II:
cout<<"Not a prime number "<<"\n";
getch();
}

goto stmt:-
In C++ programming, the goto statement is used for altering
the normal sequence of program execution by transferring
control to some other part of the program.
Syntax of goto Statement
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. ineligible:
6. cout<<"You are not eligible to vote!\n";
7. cout<<"Enter your age:\n";
8. int age;
9. cin>>age;
10. if (age < 18){
11. goto ineligible;
12. }
13. else
14. {
15. cout<<"You are eligible to vote!";
16. }
17. }

You aoutput eligible to vote!


Enter your age:
16
You are not eligible to vote!

question:- define looping stmt in c++ with an example


ans:-
C++ programming language provides the following type of
loops to handle looping requirements.
Sr.No Loop Type & Description
1 while loop
Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the
loop body.
2 for loop
Execute a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at
the end of the loop body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’
or ‘do..while’ loop.
The Infinite Loop
A loop becomes infinite loop if a condition never becomes
false. The for loop is traditionally used for this purpose. Since
none of the three expressions that form the ‘for’ loop are
required, you can make an endless loop by leaving the
conditional expression empty.
#include <iostream>
using namespace std;

int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}

return 0;
}
example of for loop
#include <iostream>
using namespace std;

int main()
{
for (int i = 1; i <= 5; i++)
{
cout << " Good morning \n";
}
return 0;
}
example of while loop
22
You are eligible to vote!

Enter your age:


7
example of do while loop

example of switch stmt

return 0;
}

ques:- define inline function with an example?


ans:- An Inline function is a function that is expanded in line
when it is called, saving time. The compiler substitutes the
corresponding function code for the function call, reducing
the overhead of function calls.

#include <iostream>
using namespace std;
inline int cube(int x)
{
return x*x*x;
}
int main()
{
cout << "Our cube is: " << cube(3) << "\n";
return 0;
}
ques:- define scope resolution operator in c++?
ans:- i) to distinquish between local and global variable
ii) to associate member function outside a class

example of compairing three numbers using nested if

ques:- pattern program

#include<iostream>
using namespace std;
int main()
{
int i, j;
for(i=0; i<6; i++)
{
for(j=0; j<=i; j++)
cout<<"* ";
cout<<endl;
}
cout<<endl;
return 0;
}
output

ques:- define diff between structure and class?


ans:-
A structure is a grouping of variables of various data types
referenced by the same name. In C++, a class is defined as a
collection of related variables and functions contained within
a single structure. If no access specifier is specified, all
members are set to 'public'.
The main difference between Structure and Class in C++ is
that Structure is a value type data type while Class is a
reference type data type.

Structure and class are two programming concepts in C++.


C++ is a high level, general-purpose programming language
that is a superset of C language as it consists of many
advanced features. There are mainly two types of data; they
are the called value type and reference type. In value type, a
value is assigned to a variable directly. In reference type data,
a variable does not store the actual data. It stores a reference
to that particular data

You might also like