100% found this document useful (1 vote)
12 views41 pages

Oops

Uploaded by

misra.arav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
12 views41 pages

Oops

Uploaded by

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

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 producTvity by allowing mulTple programmers
to work on different parts of the project independently at the
same Tme.
d) Modules can be re-used many Tmes, thus it saves Tme,
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] KriTka M: Disadvantages of Structured
Programming
a) Since GOTO statement is not used, the structure of the
program needs to be planned meTculously.
b) Lack of encapsulaTon.
c) Same code repeTTon.
d) Lack of informaTon 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 sogware 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 funcTons (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 collecTve focus.

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


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

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


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

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


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

8) The OOP supports polymorphism of operaTons.

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


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

10) The structured programming normally emphasized on


single exit point in their consTtuent funcTons or procedures.
Since each funcTon/procedure allocates some memory to
itself for storing the values of its variables and code, before
the exit, there must be a provision for deallocaTng this
memory. Otherwise, more and more of the memory gets
occupied by each funcTon/procedure and in large programs,
there may occur a shortage of m…
[8:35 am, 21/9/2024] KriTka M: QUES:- Define class?
Ans:- class is an object template. Every object under that
class has the same data format, definiTon and responds in
the same manner to an operaTon. 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 alributes (data
members/characterisTcs) and a set of acTons or
services(funcTon members/methods).
class Class_name
{
private :
variable declaraTon;
funcTon declaraTon;
public :
variable declaraTon;
funcTon declaraTon;
protected :
variable declaraTon;
funcTon declaraTon;
};
Let us see, how Employee class is defined
class Employee
{
int id;
char name[25];
char depl[25];
public:
void get_data(void)
{
cout<< “Enter Employee ID:” <<endl;
cin>>id;
cout<<”Enter name:”<<endl;
cin>>name;
cout<< “Enter department:”<<endl;
cin>>depl;
}
void display_informaTon(void)
{
cout<< “Employee ID=” <<id<<endl;
cout<< “Employee Name=” <<name<<endl;
cout<< “Employee Department=” <<depl<<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 InformaTon:"<<endl;
e1.get_data(); // object e1 calls member get_data()
cout<<"\nEnter 2nd Employee Basic InformaTon:"<<endl;
e2.get_data(); // object e2 calls member get_data()
cout<<"\n1st Employee Basic InformaTon:"<<endl;
e1.display_info(); // object e1 calls member display_info()
cout<<"\n 2nd Employee Basic InformaTon:"<<endl;
e2.display_info(); // object e2 calls member display_info()
}
OBJECT:- objects are the basic run-Tme enTTes in Object-
Oriented programming language. They occupy space in
memory that keeps its state and is operated on by the
defined operaTons on the object, while a class defines a
possible set of objects. The relaTonship between a class and
objects of that class is similar to the relaTonship 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 secTon we will see as to how object is created. The
declaraTon 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 instanTated in order to make use of the
services provided by it. This process of creaTng objects
(variables) of the class is called class instanTaTon or
instanTaTng of objects. Thus, an object is an instanTaTon of
a class. The common syntax of instanTaTng object of a class /
declaraTon 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); //declaraTon
void maximum(void); //declaraTon
void minimum(void) //definiTon
{
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 maTx
operaTon in c++?
ANS:-
Passing Objects as Arguments We can pass objects as
arguments to a funcTon 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 funcTon and any
modificaTons made to the object inside the funcTon are not
reflected in the object used to call the funcTon. While, in
pass-by-reference, an address of the object is passed to the
funcTon and any changes made to the object inside the
funcTon is reflected in the actual object. Furthermore, we
can also return object from the funcTon like any other data
type
Objects and Classes Consider the following C++ program for
addiTon and mulTplicaTon 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 AddiTon of X & Y :"<<endl;
Result=X.add(Y);
Result.display_matrix();
cout<<"\n MulTplicaTon of X & Y :"<<endl;
X.mul(Result,Y); //result=X*Y
Result.display_matrix();
}
ques:- Define encapsulaTon?
Ans:- encapsulaTon is a process of wrapping similar code in
one place. In C++, we can bundle data members and
funcTons 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 funcTon 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
funcTon getArea() are kept together in the Rectangle class.
Ques:- Define data abstracTon?

Ans:- AbstracTon 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 transmiled over network to the recipient is
hidden from you (because it is irrelevant to you).

the core principle of implemenTng abstracTon in C++ is


permission labels that determine how the data is accessed in
a program. To impose restricTons on data members of a
class, we can use permission labels as follows:
• Public - Data members and member funcTons declared
as public can be accessed from anywhere the class is visible.
• Private - Data members and member funcTons declared
as private can only be accessed within the class. Outside of
the class, they are inaccessible.
• Protected – Data members and member funcTons can
be accessed by their friend class and derived class only.
Using the aspects above given by permission labels, we can
implement abstracTon. Say, in a class, the members who
determine the internal implementaTon can be classified as
private.
And it is possible to mark the essenTal 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 abstracTon using permission labels:
#include <iostream>
using namespace std;

class abstracTon
{
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()
{
abstracTon 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()
funcTon to set the values x and y. The display() funcTon is
called to display the values x and y.
Advantages of data abstracTon
• It prevents the user from wriTng low-level code.
• It prevents duplicaTon of sogware and increases
reusability.
• The internal class implementaTon can be altered
without impacTng the user.
• It helps to improve the privacy of an applicaTon or
program as the user is only presented with relevant
informaTon.
QUES:- Define friend FuncTon?
Ans:- A friend funcTon in C++ is defined as a funcTon that can
access private, protected and public members of a class. The
friend funcTon is declared using the friend keyword inside
the body of the class
• Even though the prototypes for friend funcTons appear
in the class definiTon, friends are not members funcTons.
• We can declare friend funcTons anywhere in a class
definiTon, that is either in public, private or protected
secTons.
• We can do friend declaraTons anywhere in a class
definiTon, i.e. either in public, private or protected secTons.
• 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 relaTon is neither symmetric nor
transiTve.
Friend relaTonship cannot be inherited.
Benefits of friend funcTon
• A friend funcTon is used to access the non-public
members of a class.
• It allows to generate more efficient code.
• It provides addiTonal funcTonality which is not normally
used by the class.
• It allows to share private class informaTon by a non
member funcTon

CharacterisTcs:-
• The funcTon 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 funcTon 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 funcTon
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 staTc member?
Ans:- staTc members are data members (variables) or
methods that belong to a staTc or a non staTc class itself,
rather than to objects of the class. StaTc members always
remain the same, regardless of where and how they are used.
Because staTc members are associated with the class, it is
not necessary to create an instance of that class to invoke
them.
Since a staTc 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 staTc members are as follows:
• A staTc member has access to all staTc members of its
containing class, including private members.
• A staTc member can be declared using access control
modifiers.
• A staTc member class can use any other staTc member
without qualifying its name with the name of the containing
class.
ProperTes of staTc member funcTons:
1. A staTc funcTon can only access other staTc variables or
funcTons present in the same class
2. StaTc member funcTons are called using the class name.
Syntax- class_name::funcTon_name( )
example
#include <iostream>

using namespace std;


class Example{
staTc int Number;
int n;

public:

void set_n(){

n = ++Number;
}

void show_n(){

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

staTc 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’. StaTc member variables and
funcTons are used when common values are to be shared
across all the objects. While programming, the use of staTc
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 funcTon called constructor for
iniTalizing an object when it is created. This is known as
automaTc iniTalizaTon of objects.

• They should be declared in the public secTon.


* 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++ funcTons, they can have default arguments.
* Constructors can’t be virtual.
* Constructor can be inside the class definiTon or outside the
class definiTon.
* Constructor can’t be friend funcTon.
* They can’t be used in union.
* They make implicit calls to the operators new and delete
when memory allocaTon is required.
When a constructor is declared for a class, iniTalizaTon of the
class objects becomes necessary ager declaring the
constructor
C++ constructors have the following limitaTons:

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


means that we cannot signal an error, during the object
iniTalizaTon. The only way of doing it is to throw an
excepTon 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 Tme bound At the Tme when we create an object,


we must specify the name of a concrete class which is known
at compile Tme. There is no way of dynamic binding
constructors at run Tme.
* There is no virtual constructor We cannot declare a virtual
constructor. We should specify the exact type of the object at
compile Tme, so that the compiler can allocate memory for
that specific type. If we are construcTng derived object, the
compiler calls the base class constructor first and the derived
class hasn't been iniTalized 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 iniTalized”<<end1;
}
};
void main ()
{
student x,y,z;
getch();
}

QUES: DEFINE COPY CONSTRUCTOR? WITH AN EXAMPLE?


ANS:- A copy constructor is used to declare and iniTalize an
object from another objectThus the process of iniTalizing
through a copy constructor is known as copy iniTalizaTon. 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 situaTons
* The iniTalizaTon of an object by another object of the same
class.
* Return of objects as a funcTon value.
* StaTng 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
funcTon is defined in a class, then it is called constructor
overloading or use of mulTple 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 iniTalize
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-
iniTalize 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 funcTon that has the same
name as that of the class but is prefixed with a ~ (Tlde).
Destructor takes no arguments or specifies a return value, or
explicitly returns a value not even void. It is called
automaTcally 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 declaraTon
{ cout <<"Thanx for using this program" <<endl;
}
void main()
{ clrscr();
student s1; // s1 is an object
getch();
}

The main applicaTon and characterisTcs of destructors are


given as follows:
1. Destructor funcTons are invoked automaTcally 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 iniTalized before the object goes out of the scope
4. Destructor funcTon, also obey the usual access rules of as
other member funcTon 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 staTc.
8. It is not possible to take the address of destructor.
9. Member funcTon 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.

LimitaTons of destructors: C++ destructors have mainly two


disadvantages:
1) They are case sensiTve.
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


allocaTng and freeing memory blocks in efficient and
convenient way. The fundamental issue is the determinaTon
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 saTsfy future memory
requests. Constructors and destructor are used in C++
programming language to iniTalize and destroy the memory
blocks, when it is no longer required by the program. In
manual memory allocaTon, this is also specified manually by
the programmer; at the Tme of wriTng the codes by
programmer.
QUES:- DEFINE MEMBER FUNCTIONS?
ANS:-
A member funcTon performs an operaTon required by the
class. It is the actual interface to iniTate an acTon 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 funcTons of a class can be defined in two places:
(i) inside the class definiTon
(ii) (ii) outside the class definiTon
iii) The syntax of a member funcTon definiTon changes
depending on whether it is defined inside or outside the class
declaraTon/definiTon. However, irrespecTve of the locaTon
of their definiTon, the member funcTon must perform the
same operaTon. Thus, the code inside the funcTon body
would be idenTcal in both the cases. The compiler treats
these two definiTons in a different manner. Let us see, how
we can define the member funcTon inside the class
definiTon. The syntax for specifying a member funcTon
declaraTon is similar to a normal funcTon definiTon 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 invocaTon. 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:
// creaTng parameterized constructor
rectangle(double len, double brt) {
// iniTalize private variables
length = len;
breadth = brt;
}
double calculateArea() {
return length * breadth;
}
};
int main() {
// creaTng objects and iniTalizing 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 funcTon is defined in a
class, then it is called constructor overloading or use of
mulTple 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 iniTalize 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 condiTon
if (i == 3) {
break;
}
cout << i << endl;
}

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

// program to print the value of i

#include <iostream>
using namespace std;

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

cout << i << endl;


}

return 0;
}
Output
1
2
4
5

exit stmt

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


program. The value supplied as an argument to exit is
returned to the operaTng system as the program's return
code or exit code. By convenTon, 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 execuTon 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!

quesTon:- 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 & DescripTon
1 while loop
Repeats a statement or group of statements while a given
condiTon is true. It tests the condiTon before execuTng the
loop body.
2 for loop
Execute a sequence of statements mulTple Tmes and
abbreviates the code that manages the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condiTon 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 condiTon never becomes
false. The for loop is tradiTonally 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
condiTonal expression empty.
#include <iostream>
using namespace std;

int main () {
for( ; ; ) {
prinâ("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 funcTon with an example?


ans:- An Inline funcTon is a funcTon that is expanded in line
when it is called, saving Tme. The compiler subsTtutes the
corresponding funcTon code for the funcTon call, reducing
the overhead of funcTon 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 resoluTon operator in c++?


ans:- i) to disTnquish between local and global variable
ii) to associate member funcTon outside a class

example of compairing three numbers using nested if

ques:- palern 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
collecTon of related variables and funcTons 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 parTcular data

You might also like