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

Assg2_OOP_solution

Uploaded by

Maniya Daxit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Assg2_OOP_solution

Uploaded by

Maniya Daxit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Object Oriented Programming (C++) SY BCA SEM – III

Objective Questions (2 marks)


1. What is default constructor ?
A constructor that does not have any arguments(parameters) is called default
constructor.
If no such constructor is defined, then the compiler supplies a default constructor.
Example :
class A void main()
{ {
int x; A obj; // implicitly called default constructor
public : getch();
A() // default constructor }
{
x = 0; // initialize with zero
}
}

2. What is copy constructor ?


A constructor which have a reference to its own class as a parameter is called copy
constructor.
It is used to declare and initialize an object from another object.
When no copy constructor is defined, the compiler supplies its own copy constructor.
Example :
class A void main()
{ {
int x; A obj1;
public : A obj2(obj1); // called copy constructor
A() { x = 10;} A obj3 = obj1; //also called copy constructor
A( A & ob) //copy constructor A obj4;
{ obj4 = obj1; // does not called copy constructor
x = ob.x; getch();
} }
}

3. What is the advantage of new over malloc ? (Prof. Viral S. Patel)


It automatically computes the size of data object. We need not use the operator sizeof();
It automatically returns the current pointer type so there is no need to type cast.
Like any other operator new and delete can be overloaded.
It is possible to initialize the object while allocating the memory.
---------------------------------------------------------------------------------------------------------------------------
*note :

malloc() malloc stands for "memory allocation". Allocates requested size of bytes and
returns a pointer first byte of allocated space

Syntax:
ptr = (cast-type*) malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an


area of memory with size of byte size. If the space is insufficient, allocation fails
and returns NULL pointer.

Example :
Object Oriented Programming (C++) SY BCA SEM – III

ptr = (int*) malloc(100 * sizeof(int));

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.

calloc() Allocates space for an array elements, initializes to zero and then returns a
pointer to memory (Prof. Viral S. Patel)

ptr = (cast-type*)calloc(n, element-size);

This statement will allocate contiguous space in memory for an array


of n elements.
Example :
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25
elements each of size of float, i.e, 4 bytes.

free() deallocate the previously allocated space


free(ptr);

realloc() Change the size of previously allocated space


ptr = realloc(ptr, newsize);

---------------------------------------------------------------------------------------------------------------------------

4. Define Destructor. How can you invoke a destructor ?


A destructor, as the name implies, is used to destroy the objects that have been created
by a constructor.
A destructor never takes any argument nor does it return any value.
It will be invoked implicitly by the complier upon exit from the program or block or
function as scope of object is just going to end.
[ * If we do not write our own destructor in class, compiler creates a default destructor for
us. The default destructor works fine unless we have dynamically allocated memory or
pointer in class. When a class contains a pointer to memory allocated in class, we should
write a destructor to release memory before the class instance is destroyed. This must be
done to avoid memory leak. (Prof. Viral S. Patel) ]

5. What is significance of new and delete ?


new : We can allocate memory at run time within the heap for the variable of a given type
using a special operator in C++ which returns the address of the space allocated. This
operator is called new operator.
delete : If we are not in need of dynamically allocated memory anymore, we can
use delete operator, which de-allocates memory previously allocated by new operator.
Example :
int *p; // p is integer pointer
p = new int; // dynamically(run time) allocate two byte memory to store integer value
p = new int(5); // dynamically (int-two byte) memory given to pointer p and assign value 5
p = new int[5]; // dynamically allocate integer array of size 5 to pointer p
Object Oriented Programming (C++) SY BCA SEM – III

delete p; // release the memory space given to p


delete []p; // delete the entire array pointed by p

6. What is constructor with default argument ? (Prof. Viral S. Patel)


 It is possible to define constructors assigns a default value to the parameter which does
not have a matching argument in the constructors call. For example,

A(int i, int k = 10) //Constructor


{
P = i;
Q = k;
}

A obj1(2); // object created and constructor calling statement


result : P =2 and Q=10 (take default value).

A obj2(3,4); // object created and constructor calling statement


Result : P =3 and Q=4.

Ambiguity : some time situation created like default constructor A::A() and the default
argument constructor A::A(int = 0) forms are created ambiguity as compiler cannot decide
whether to call A::A() or A::(int =0) when called with no arguments.

7. List out the operators that cannot be overloaded as member and friend function.

Operators that cannot be overloaded using Operators that cannot be overloaded using
member function friend function
. Membership operator = Assignment operator
.* Pointer-to-member operator () Function call operator
:: Scope resolution operator [] Subscripting operator
?: Conditional operator -> Class member access operator

8. What do you mean by operator overloading ? Give Syntax for it.


C++ has the ability to provide the operators with a special meaning for a user defined data
type. The mechanism of giving such special meaning to an operator is known as operator
overloading.
For example, C++ permits us to add two variables of user-defined types with the same
syntax that is applied to basic types.
Syntax : return type classname :: operator op(arglist)
{
function body // task defined
}

Long Questions :
1. List memory management operators. Point out reasons why using new is better idea than
using malloc() ? (5) (Prof. Viral S. Patel)
new and delete are memory management operator.

new operator is better because of following advantages over malloc function :

For example : int *ptr = (int*) malloc(100 * sizeof(int))


int *ptr = new int[100];
Object Oriented Programming (C++) SY BCA SEM – III

 new automatically computes the size of data object. We need not use the operator
sizeof(). In given example pointer ptr have 200 bytes memory to store 100 integer values. In
malloc we have used sizeof to calculate the size of int bytes and in new operator no need of
it.
 new automatically returns the current pointer type so there is no need to type cast.
In given example for malloc we have to first casting memory to (int *) then we can give it to
ptr. In new operator no need of type casting.

Like any other operator new and delete can be overloaded. malloc function cannot be
used for other purpose.

It is possible to initialize the object while allocating the memory.


For example, int *p = new int(5);
Here pointer p points 2 byte memory which have value 5.

2. What do you mean by default argument ? When it is useful ? (5) (Prof. Viral S. Patel)

C++ allows us to call a function without specifying all its arguments. In such cases, the
function assigns a default value to the parameter which does not have a matching argument
in the function call.

Example :

int mul(int i, int k = 10) //function defination


{
int val;
val = i * k;
return val;
}

value = mul(2); // function calling

Here function calling give answer 20 as pass value 2 in variable i and value of k is default 10.

Rules : Only the trailing arguments can have default values and therefore we must add
defaults from right to left.

Useful when :
1. Some Situations where some arguments always have the same value. For example,
bank interest may remain the same for all customers for a particular period of
deposit.
2. we can use default arguments to add new parameters to the existing functions.
3. Default arguments can be used to combine similar functions into one.

3. What is destructor ? How destructor get called ? Also describe the importance of destructor.
(5) (Prof. Viral S. Patel)
A destructor, as the name implies, is used to destroy the objects that have been created
by a constructor and releases memory space for future use.
Like a constructor, the destructor is a member function whose name is the same as the
class name but is preceded by a tilde.
For example, ~A(){ }
A destructor never takes any argument nor does it return any value.
Object Oriented Programming (C++) SY BCA SEM – III

It will be invoked implicitly by the compiler upon exit from the program or block or
function as scope of the object end. Objects are destroyed in the reverse order of creation.
It clean up storage that is no longer accessible.
Whenever new is used to allocate memory in the constructors, we should use delete to
free that memory. This is required because when the pointers to objects go out of scope, a
destructor is not called implicitly.

4. What is constructor ? How do we call a constructor ? State the advantages of constructor.


(7)
A constructor is a special member function whose task is to initialize the objects of its
class. Its name is the same as the class name. It is called constructor because it constructs
the value of data members of the class.
It do not have return types so it cannot return value. They cannot be virtual.
They can have default arguments.

The constructor is invoked automatically (implicitly) whenever an object is created.


Constructor is also calling by explicitly. (Prof. Viral S. Patel)

Example :
class A A(int a,int b) // parameterized constructor
{ {
int x; x=a; y=b;
int y; }
public : };
A() // default constructor void main()
{ {
x = 10; y=20; A obj1; // called default constructor implicitly
} A obj2(obj1); // called copy constructor
A( A & ob) //copy constructor A obj3 = obj1; // also called copy constructor
{ A obj4(5,6); // called parameterized constructor
obj1 = A(2,3) // explicitly called parameterized constructor
x = ob.x; y = ob.y;
getch();
}
}

Advantages :
No need of calling statement for constructor as it is invoked automatically.
When necessary we can also called it as explicitly.
We cannot refer to their addresses. So it is secured.
We can initialize the object just after it is created.
We can make copy of object by using copy constructor.
Compiler supply default and copy constructor if we have not created.
They make implicit calls to the operators new and delete when memory allocation is
required.

5. Define constructor. Explain default and copy constructor. (7)


[ see objective question 1 & 2 for answer] (Prof. Viral S. Patel)

6. Explain parameterized constructor. (5)


The constructors that can take arguments are called parameterized constructors. By
using parameterized constructors to initialize the various data elements of different objects
with different values when they are created.
Object Oriented Programming (C++) SY BCA SEM – III

Example:
class A void disp()
{ {
int x; cout<<x<< “ “<<y;
int y; }
public : };
A(){ } void main()
A(int a,int b) // parameterized constructor {
{ A obj1(2,3), obj3;
x=a; y=b; // obj1 call to parameterized constructor
} A obj2(obj1); // call to copy structor
A( A & ob) //parameterize copy constructor A ob3 = A(4,5); // explicitly call
obj1.disp(); // output : 2 3
{
obj2.disp(); // output : 2 3
x = ob.x; y = ob.y; obj3.disp(); // output : 4 5
} getch();
}

We can pass the parameters in two ways : pass by value or pass by reference.
We can call parameterized constructor two ways : explicitly and implicitly.
A obj1(2,3) is implicit call in above program.
A obj3 = A(4,5) is explicit call in above program.
We cannot pass object of same class in parameter. But we can pass reference of it.
A(A) is illegal
A(A&) is valid. It is called copy constructor.
In above example, A obj2(obj1) calling to copy constructor. And obj1 pass as reference.
These constructors can also be inline, same as inline function.

(5&6 : What is constructor ? Explain different types of constructor.(7) ) (Prof. Viral S. Patel)

7. Write a program to create a class scale. Define two variable feet and inches. Define member
function getscale, putscale and sum function to add to measure passed object as argument
to the function sum. (7)

#include<iostream.h>
#include<conio.h>
class scale
{
int feet;
int inches;
public : void getscale()
{
cout<<"Feet :";
cin>>feet;
cout<<"Inches :";
cin>>inches;
}
void putscale()
{
cout<<feet<< " " <<inches;
}
scale sum(scale & o2)
Object Oriented Programming (C++) SY BCA SEM – III

{
scale temp;
int tot_inch = inches + o2.inches;
temp.feet = feet + o2.feet + (tot_inch / 12);
temp.inches = tot_inch % 12;
return temp;
}
};
void main()
{
scale obj1,obj2,obj3;
clrscr();
obj1.getscale();
obj2.getscale();
obj3=obj1.sum(obj2);
obj3.putscale();
getch();
}
(Prof. Viral S. Patel)

8. What is conversion function ? How it is created ? Explain with example. (5)


The conversion function also know as casting operator function.
It is used to convert class to basic type. It is used in source class for class to class type
conversion. (Prof. Viral S. Patel)
Syntax :
operator typename()
{
...... function statements .....
}
Casting operator function should satisfy the following conditions :
 It must be a class member.
 It must not specify a return type.
 It must not have any arguments.

Example :
class BILL void main()
{ {
int items; BILL ob(5,20);
int price; int total_price;
public :
BILL(int i, int p) total_price = ob; // call casting operator function
{ //also called as total_price = ob.operator int();
items = i; price = p; cout<<total_price;
}
operator int() // casting operator getch();
{ }
return (items * price); Output : 100
}
};
Object Oriented Programming (C++) SY BCA SEM – III

9. Differentiate between Unary and Binary operator overloading. (7)


Unary operator overloading Binary operator overloading
Unary Member function have no argument. Binary member function have one
One object invoke the member function is argument. One object invoke the member
passed implicitly. function and another operand/object must
be passed as argument.
Unary operator member function example : Binary operator member function example :

void operator-() friend vector operator+(vector v)


{ {
.... ....
} }

Unary member Function Calling example : Binary member Function Calling example:

ob.operator –(); ob3= ob1.operator-(ob2);


Or Or
-ob ob3 = ob1 + ob2;

Unary Friend function have only one Binary Friend function have two arguments.
argument.
Unary Friend function example : Binary friend function example :

void operator -(vector & v) friend vector operator+(vector v1,vector v2)


{ {
... ...
} }
Unary friend function calling example : Binary friend function calling example :

operator-(ob); ob3 = operator+(ob1,ob2);


or or
-ob; ob3 = ob1+ob2;
In Unary member function there is no calling In Binary member function calling sequence
sequence problem as only one object is problem generated.
used.
For example :
ob2 = ob1 +3 ;
And
ob2 = 3 + ob1; //error for member function
// 3 cannot be used to call function as it is
not object.

left hand operand must be an object in


binary operator overloading function.

10. What is overloading of an operator ? When it is necessary to overload an operator ?


Operator overloading provides a flexible option for the creation of new definitions for
most of the C++ operator. (Prof. Viral S. Patel)
Operators used with basic data types will not work directly with user defined types. C++
has the ability to provide the operators with a special meaning for this user defined data
type.
Object Oriented Programming (C++) SY BCA SEM – III

For overloading the operator a special function is used called operator function.
Syntax :
return type classname :: operator op (arglist)
{
Function body
}
Operator function may be member function or friend function.
Operator function may be for unary or binary operators.
[ * note : Write here answer of question no. 9 for unary and binary operator overloading]

11. Write rules for operator overloading. Give example. (6)


[* note : Read 7.8 rules for overloading operators from book Balagurusamy, Ch. No. 7]

12. How many arguments are required in the definition of an overloaded unary operator ? Why
? (7)
[* note : Read answer of question no. 9 for unary operator ] (Prof. Viral S. Patel)

13. How many arguments are required in the definition of an overloaded binary operator ? Why
? (7)
[* note : Read answer of question no.9 for binary operator ]

14. What is type conversion ? Explain basic to class type with proper example. (7)

When variables and constants of different types are mixed in an expression or different
types of operand are used left and right side of assignment operator then automatic type
conversion occur as per certain rules. But the user defined data types are designed by us to
suit our requirements , the complier does not support automatic type conversions for such
data type. (Prof. Viral S. Patel)
Three types of situations occur for user defined data type conversion.
(1) Conversion from basic type to class type
(2) Conversion from class type to basic type
(3) Conversion from one class type to another class type
Basic to class type conversion : The constructors used for this type conversion take a single
argument whose type is to be converted. Constructor is calling implicitly.
Example :

class Time void main()


{ {
int hrs; Time T1;
int mins; int duration = 85;
public : T1 = duration; // call constructor implicitly
.... ....
.... }
Time(int t)
{ After this conversion, the hrs member of T1 will containing a
hrs = t / 60; value of 1 and mins member a value of 25, denoting 1 hours
mins = t % 60; and 25 minutes.
}
} T1 = duration; // same as T1 = Time(duration);

We can also do same by using an overloaded = operator.


Object Oriented Programming (C++) SY BCA SEM – III

15. Explain different types of type conversion. (5)


Basic to class type conversion : The constructors used for this type conversion take a single
argument whose type is to be converted. (Prof. Viral S. Patel)
Example :

class Time void main()


{ {
int hrs; Time T1;
int mins; int duration = 85;
public : T1 = duration; // call constructor implicitly
.... ....
.... }
Time(int t)
{ After this conversion, the hrs member of T1 will containing a
hrs = t / 60; value of 1 and mins member a value of 25, denoting 1 hours
mins = t % 60; and 25 minutes.
}
} T1 = duration; same as T1 = Time(duration);

Class to basic type conversion : The overloaded casting operator could be used to convert a
class type data to basic type.

The overloaded casting operator :


 It must be a class member.
It must not specify a return type.
It must not have any arguments.

Example :

class Time void main()


{ {
int hrs; Time T1(1,25);
int mins; int duration = T1; // call to casting operator int()
public : ....
.... }
Time(int h, int m)
{ After this conversion, the duration containing value 85.
hrs = h;
mins = m; duration = T1; same as duration = T1.opeartor int();
}
operator int() (Prof. Viral S. Patel)
{
return (hrs*60 + mins);
}
}

one class to another class type conversion : This conversion takes place either by
constructor in destination class or by casting operator in source class.

Example :
Object Oriented Programming (C++) SY BCA SEM – III

....
class Dollar class Rupees We can convert class type Dollar
{ { to type Rupees either by
int d; int r; constructor in destination class
public : public : Rupees or by casting operator in
.... .... source class Dollar.
Dollar(int t) Rupees(Dollar ob)
{ {
d = t; r = ob.d * 65;
} }
.... ....
/* operator Rupees() }
{ void main()
Rupees ob; {
ob.r = d * 65; Dollar D1(3);
return ob; Rupees R1;
} R1 = D1;
*/ ....
} }

16. Explain basic to class and class to basic type conversion. (7)
[ * note : read answer of question 15 ] (Prof. Viral S. Patel)

You might also like