News

C++ basic questions and Solutions

C++ Basics “Sciencefactsblog.blogspot.com”
(ii)File pointers: we need to have file pointers viz. input pointer and output pointer. File
pointers are required in order to navigate through the file while reading or writing. There are
certain default actions of the input and the output pointer. When we open a file in read only
mode, the input pointer is by default set at the beginning. When we open a file in write only
mode, the existing contents are deleted and the file pointer is attached in the beginning.
C++ also provides us with the facility to control the file pointer by ourselves. For this, the
following functions are supported by stream classes: seekg(), seekp(), tellg(), tellp().
(iii) Function prototyping is used to describe the details of the function. It tells the compiler
about the number of arguments, the type of arguments, and the type of the return values. It
some what provides the compiler with a template that is used when declaring and defining a
function. When a function is invoked, the compiler carries out the matching process in which it
matches the declaration of the function with the arguments passed and the return type. In C++,
function prototype was made compulsory but ANSI C makes it optional. The syntax is as
follows:
type function-name(argument-list);
example int func(int a, int b, int c);
(iv)Overload resolution: When we overload a function, the function prototypes are matched
by the compiler. The best match is found using the following steps.
a. The compiler first matches that prototype which has the exactly same types of actual
arguments.
b. If an exact match is not found by the first resolution, the integral promotions to the actual
arguments are used like char to int, float to double.
c. When both the above methods fail, the built in conversions to the actual arguments are used
like long square (long n).
d. If all the above steps do not help the compiler find a unique match, then the compiler uses
the user defined convergence, in combination with integral promotions and built in
conversions.
Function:A function is a set of program statements that can be processed independer.tly. A
function can be invoked which behaves as though its code is inserted at the point of the
function call. The communication between a caller (calling function) and callee (called
function) takes place through parameters. The functions can be designed, developed, and
implemented independently by different programmers. The independent functions can be
grouped to form a software library. Functions are independent because variable names and
labels defined within its body are local to it.
The use of functions offers flexibility in the design, development, and implementation of the
program to solve complex problems. The advantages of functions includes the following:
Modular programming
Reduction in the amount of work and development time
Program and function debugging is easier
Division of work is simplitied due to the use of divide-and-conquer principle .
Reduction in size of the program due to code reusability
Functions can be accessed repeatedly without redevelopment, which in turn promotes reuse
of code .
Library of functions can be implemented by combining well designed, tested and proven
function.
Function Components
Every function has the following elements associated with it:
1. Function declaration or prototype.
2. Function parameters (formal parameters)
3. Combination of function declaration and its definition.
4. Function definition (function declaration and a function body).
5. return statement.
6. Function call.
A function can be executed using a function call in the program. The various components associated
with the function are shown in Figure
Void func(int a, int b); Function declaration
Prototype
parameter
…………
void func(int a, int b) { Function definition
…… Body
}
func(x,y); Function Call
Q.66 Explain the difference between constructor and copy constructor in C++. Which of these is
invoked in the following statement
Date D1 (D2); where D2 is also an object of class Date. (3)
Ans: Constructors are special `member functions' of which exactly one is called automatically
at creation time of an object. Which one depends on the form of the variable declaration.
Symmetrically, there exists a destructor, which is automatically called at destruction time of an
object. Three types of constructors are distinguished: default constructor, copy constructor, and
all others (user defined). A constructor has the same name as the class and it has no return type.
The parameter list for the default and the copy constructor are fixed. The user-defined
constructors can have arbitrary parameter lists following C++ overloading rules.
class A {
int i; // private
public:
A(); // default constructor
A( const A& a); // copy constructor
A( int n); // user defined
~A(); // destructor
};
int main() {
A a1; // calls the default constructor
A a2 = a1; // calls the copy constructor (not the assignment operator)
A a3(a1); // calls the copy constructor (usual constructor call syntax)
A a4(1); // calls the user defined constructor
} // automatic destructor calls for a4, a3, a2, a1 at the end of the block
The compiler generates a missing default constructor, copy constructor, or destructor
automatically. The default implementation of the default constructor calls the default
constructors of all class member variables. The default constructor is not automatically
generated if other constructors are explicitly declared in the class (except an explicit declared
copy constructor). The default copy constructor calls the copy constructor of all class member
variables, which performs a bitwise copy for built-in data types. The default destructor does
nothing. All default implementations can be explicitly inhibited by declaring the respective
constructor/destructor in the private part of the class.
Constructors initialize member variables. A new syntax, which resembles constructor calls,
allows to call the respective constructors of the member variables (instead of assigning new
values). The constructor call syntax extends also to built-in types. The order of the
initializations should follow the order of the declarations, multiple initializations are separated
by comma.
class A {
int i; // private
public:
A() : i(0) {} // default constructor
A( const A& a) : i(a.i) {} // copy constructor, equal to the compiler default
A( int n) : i(n) {} // user defined
71
Code: AC11 Subject: OBJECT ORIENTED PROGRAMMING
~A() {} // destructor, equal to the compiler default
};
Usually, only the default constructor (if the semantics are reasonable), and some user defined
constructors are defined for a class. As soon as the class manages some external resources, e.g.,
dynamically allocated memory, the following four implementations have to work together to
avoid resource allocation errors: default constructor, copy constructor, assignment operator,
and destructor. Note that the compiler would create a default implementation for the
assignment operator if it is not defined explicitly
Q.68 Why is destructor function required in class? What are the special characteristics of
destructors? Can a destructor accept arguments? (8)
Ans: Destructor: A destructor is used to destroy the objects that have been created by a
constructor. It has the same name as that of the class but is preceded by a tilde. For example,
~integer () {}
Characteristics:
A destructor is invoked implicitly by the compiler when we exit from the program or block.
It releases memory space for future use.
A destructor never accepts any argument nor does it return any value.
It is not possible to take the address of a destructor.
Destructors can not be inherited.
They cannot be overloaded
For example, the destructor for the matrix class will defined as follows:
matrix :: ~matrix()
{
for(int i=0;i<d1;i++)
delete p[i];
delete p;
Q.73 With an example highlight the benefit of operator overloading. (2)
Ans:
The operator facilitates overloading of the c++ operators. The c++ operator overloaded to
operate on member of its class.
Q.74 Explain the difference between operator member functions and operator non member
functions. (2)
Ans:
The operator overloaded in a class is known as operator member function. Using friend
functions in operator overloading then it becomes operator non member function.
Q88 What is encapsulation? What are its advantages? How can encapsulation be enforced in
C++? (6)
Ans: Encapsulation: The wrapping up of data and functions into a single unit is called
encapsulation. The data can only be accessed by the function with which they have been tied up
and not by the outside world. It creates an interface between the object’s data and the program.
A common use of information hiding is to hide the physical storage layout for data so that if it
is changed, the change is restricted to a small subset of the total program. For example, if a
three-dimensional point (x, y, z) is represented in a program with three floating point scalar
variables and later, the representation is changed to a single array variable of size three, a
module designed with information hiding in mind would protect the remainder of the program
from such a change.
In object-oriented programming, information hiding reduces software development risk by
shifting the code's dependency on an uncertain implementation (design decision) onto a welldefined
interface. Through encapsulation, we can provide security to our data function.
Encapsulation can be enforced in C++ using the concept of classes which binds data and
function together. Private data and member functions will not be visible to outside world. For
example, in the following class two members x, y declared as private can be accessed only by
the member functions, not even in main( ) we can call these data members.
class XY
{
int x,y;
public:
void getdata();
void dispdata();
};
void XY::getdata()
{ cout<< “Enter two values\n”;
cin>>a>>b;
}
void XY::dispdata()
{ cout<<a<<b;
}
void main()
{ XY xy1,xy2;
xy1.getdata();
xy2.dispdata();
(iii) Default constructor and copy constructor
Dafault constructor: A constructor that accepts no argument is called default constructor. This
default constructor takes no parameters, or has default values for all parameters. The default
constructor for the class A is A::A(). If no such constructor is defined, then the compiler
supplies a default constructor. A default parameter is one where the parameter value is supplied
in the definition. For example in the class A defined below 5 is the default value parameter.
Class A
{ int value;
Public:
A(int param=5)
{
value = param;
}
};
A copy constructor is a special constructor in the C++ programming language used to create a
new object as a copy of an existing object. This constructor takes a single argument: a reference
to the object to be copied. Normally the compiler automatically creates a copy constructor for
each class (known as an implicit copy constructor) but for special cases the programmer creates
the copy constructor, known as an explicit copy constructor. In such cases, the compiler doesn't
create one.
For example the following will be valid copy constructors for class A.
A(A const&);
A(A&);
A(A const volatile&);
A(A volatile&);
(iv)Public and Private access specifiers:
The keywords public and private are visibility labels. When the data members of a class are
declared as private, then they will be visible only within the class. If we declare the class
members as public then it can be accessed from the outside world also. Private specifier is used
in data hiding which is the key feature of object oriented programming. The use of the keyword
private is optional. When no specifier is used the data member is private by default. If all the
data members of a class are declared as private then such a class is completely hidden from the
outside world and does not serve any purpose.
class class-name
{
private:
int x,y;//No entry to private area
92
Code: AC11 Subject: OBJECT ORIENTED PROGRAMMING
private:
int a,b;//entry allowed to public area
Ans:
i) Constructor:
A constructor is a member function which has the same name as at that of the class. It is used to
initialize the data members of the class. A constructor is automatically invoked by the compiler
when an object is created. A constructor which does not take any arguments is called default
constructor.
The restrictions applied to a constructor are:
A constructor cannot have any return type as it does not return any value.
A constructor should be declared in the public part of the class.
A derived class can call the constructor of the base class but a constructor is never
inherited.
A constructor function cannot be made virtual.
That object which has a constructor cannot be used as a member of the union.
C++ provides us with very helpful feature i.e., copy constructor. It is the mechanism in which
we can declare and initialize an object from another both belonging to the same class. For
example, the following statement will create an object obj2 and also initialize it by taking
values from obj1.
integer obj2(obj1);
We can also use the following instead the above for the same purpose.
integer obj2=obj1;
This process of initializing objects using copy constructor is known as “copy initialization”.
Another statement obj2=obj1 will not assign the values using the copy constructor. Although
the statement is valid this can be done using operator overloading.
A copy constructor accepts a reference to an object of the same class as an argument. We
cannot pass an argument by value to a copy constructor.
The following is an example program
Q.129 Discuss the role of inheritance in object-oriented programming. What is public, private and
protected derivation? (8)
Ans:
Inheritance: it is the property by which one class can be derived from another class such that it
acquires the properties of its base class. Just like a child inherits the properties of its parents in
the same way OOP allows us to reuse the members and functions of class to be derived by
another class. There are many different kinds of inheritance like multiple inheritance,
multilevel inheritance and hierarchical inheritance.
The visibility mode specified while declaring a derived class plays a very important role in the
access control of the data members of the class. The visibility mode is one of the three
keywords: public, private and protected. These access specifiers determine how elements of the
base class are inherited by the derived class. When the access specifier for the inherited base
class is public, all public members of the base class become public members of the derived
class. If the access specifier is private, all public members of the base class become private
members for the derived class. Access specifier is optional. In case of a derived ‘class’ it is
private by default. In case of a derived ‘structure’ it is public by default.
The protected specifier is equivalent to the private specifier with the exception that protected
members of a base class are accessible to members of any class derived from the base. Outside
the base or derived class, protected members are not accessible. The protected specifier can
appear anywhere in the class.
When a protected member of a base class is inherited as public by the derived class, it becomes
protected member of the derived class. If the base is inherited a private, the protected member
of the base becomes private member of the derived class.
Q.136 What do you mean by operator overloading? How unary and binary operators are
implemented using the member and friend functions? (8)
Ans: When an operator is overloaded it doesn’t lose its original meaning but it gains an
additional meaning relative to the class for which it is defined. We can overload unary and
binary operators using member and friend functions.
When a member operator function overloads a binary operator the function will have only one
parameter. This parameter will receive the object that is on right of the operator. The object on
the left side is the object that generates the call to the operator function and is passed implicitly
by “this”.
Overloading a unary operator is similar to overloading a binary operator except that there is
only one operand to deal with. When you overload a unary operator using a member function
the function has no parameter. Since there is only one operand, it is this operand that generates
the call to the operator function.
Overloading operator using a friend function: as we know that a friend function does not have a
‘this’ pointer. Thus in case of overloading a binary operator two arguments are passed to a
friend operator function. For unary operator, single operand is passed explicitly. We cannot use
a friend function to overload an assignment operator(=).
Q.137 Explain the importance of using friend function in operator overloading with the help of an
example. (4)
Ans: We can overload operators using both member function and friend functions. There are
certain cases when we prefer using a friend function more than a member function. For
examples suppose we wish to pass two different types of operands to the operator function, one
of the operands may be an object and the other may be an integer. In case of overloading a
binary operator:
A = ob + 4; or A = ob * 2;
The above statement is valid for both a member function and a friend function. But the opposite
is not valid for a member function:
A = 4 + ob; or A = 2 * ob;
This statement is valid only in case of a friend function. This is because the left hand operand
should be an object as it is used to invoke a member operator functiion

2 comments :