Cognizant Most Frequently Asked C++ Interview Questions Answers
Discuss The Effects Occur, After An Exception Thrown By A Member Function Is Unspecified By An Exception Specification?
When a function throws an exception, not given in the specification, the exception is passed to a system function named unexpected. The unexpected function calls the latest function named as an argument in a call to the set_unexpected function, which returns its current settings. A function with no exception specification, by default, calls the terminate function, which finally calls the abort (function to terminate the program).
How Can I Be Thrown Polymorphically?
The following code can be used to throw i polymorphically
classExceptionParent { );
classE,cceptionChild : public ExceptionParent ( );
void f(ExceptionParent8 e)
/1
throw e;
void go
ExceptionChild e;
try(
fCc);
catch (ExceptionChild& e) (
//...code to handle ExceptlonChild...
catch C...) (
//...code to handle other exceptions...
)
)
In the preceding code, you can enter the catch (...) clause in the absence of throwing i polymorphically. The throw e in the function f () throws the same type of an object as an expression of static type.
What Is The Role Of Copy Constructor In Copying Of Thrown Objects?
A copy constructor with a public access specifier must be applied to the objects which are thrown.With the help of a compiler, the code is generated through which copying of thrown objects can be done. The thrown objects must have a copy constructor with the public access specifier.
How Can An Improvement In The Quality Of Software Be Done By Try/catch/throw?
Error-handling is necessity while developing applications to account for unexpected situations, such as insufficient memory, resource allocation errors, inability to find/open files, division by zero, an arithmetic or array overflow, and the exhaustion of free heap space, which occur at runtime.
Programmers have various styles of dealing with such exceptions, such as try/catch /throw methods, which cause diversity in coding practice. This diversity increases with the use of user-defined classes, as each class brings with it potential class-specific errors. These methods provide a standard facility to deal with runtime exceptions. Moreover, try/catch/throw result in the code with fewer errors. It is low in cost in relation to development. With error-handling, your program can detect unexpected events and recover from them.
What Is A Dangling Pointer?
When the location of the deallocated memory is pointed by the pointer even after the deletion or allocation of objects is done, without the modification in the value of the pointer, then this type of pointer is called a dangling pointer.
Explain The Concept Of Memory Leak.
When a variable does not exist longer in the memory, and deletion or reuse of that variable cannot be done, then its destruction occurs automatically. This concept is called memory leak.
For example, consider the following code snippet
{
parent*p=new parent();
}
In the preceding code snippet, the p variable does not exist in the memory, but the variable is not deleted. Therefore, it becomes out of scope and its destruction occurs, which results in memory leak.
List The Issue That The Auto_ptr Object Handles?
The auto_ptr object is used to deallocate memory, which is allocated to a variable, when the variable goes out of scope.
What Are Smart Pointers?
Smart pointers are almost similar to pointers with additional features, such as automatic destruction of a variable when it becomes out of scope and the throwing of exceptions that ensures the proper destruction of the dynamically allocated objects. They are useful in keeping tracks of dynamically allocated objects. Due to these additional capabilities, they reduce the possibilities of occurrence of exceptions and errors in a program and ensure that the written code is safe and efficient.
How A Pointer Differs From A Reference?
A pointer differs from a reference in the following ways
In the case of reference, an object must always be referred while initializing. On the contrary, such restrictions are not meant for pointers.
The different types of objects can be pointed by the pointers by reassigning the pointers with different objects. On the contrary, in a reference, the same object which was initialized earlier can only be referred by a reference.
You can use a null address in a pointer parameter to indicate that a variable does not exist; whereas, there is no existence of a null reference in C++.
A reference usually appears outside an object; whereas, a pointer generally appears inside an object.
How Const Int *ourpointer Differs From Int Const *ourpointer?
As a rule, pointer declarations should be read from right to left. In the pointer declaration, const int *ourPointer, ourPointer is a pointer to a const int object, which cannot be changed by using a pointer. Whereas in case of the int const *ourPointer pointer declaration, ourPointer is a const pointer to an int object, in which an int object can be changed by using a pointer but the pointer itself cannot be changed because it is constant.
Explain How Overloading Takes Place In C++?
C++ supports two types of overloading namely, function overloading and operator overloading. Function overloading helps in defining more than one function with the same name, but with different signatures. An error is raised if two overloaded functions are provided with the same function signature. Operator overloading helps in giving special meanings to operators, when they are used with user-defined classes.
What Is The Difference Between Prefix And Postfix Versions Of Operator++()?
The prefix and postfix versions of operator ++() can be differentiated on the basis of arguments defined. The postfix operator ++() consists of a dummy parameter of int datatype; whereas, a dummy parameter is not found in the prefix operator ++().
Describe The Advantages Of Operator Overloading?
Operator overloading is used to provide some extra features, behaviors, and abilities to the users of a particular class. This feature in C++ helps in controlling the functions performed by an operator and reduces the chance of occurrence of errors in a program.
Provide Some Examples Of Operator Overloading?
The implementation of operator overloading is done in the following ways
Concatenating two std:-.string objects by using the + operator
Incrementing a Date object by using the ++ operator
Multiplying two different number objects by using the * operator
Accessing array elements from an object of the Array class by using the subscript operator
Can The Operator == Be Overloaded For Comparing Two Arrays Consisting Of Characters By Using String Comparison?
The operator == cannot be overloaded to compare two arrays consisting of characters using string comparisons. It should be noted that out of the two operands of an overloaded operator, at least one operand should be of user- defined type. This user-defined type usually refers to a class. Two characters can be compared easily using classes, such as std::string, rather than using an array containing characters.
Can The Creation Of Operator** Is Allowed To Perform The To-the-power-of Operations?
No, you cannot create operator** for to-the-power-of operations. The number of parameters taken by an operator, names of the operators, priority level of the operators, and the associativity of the operators depend on language in which they are being used. The operator** is not present in C++, so it cannot be created.
What Is The Main Purpose Of Overloading Operators?
The main purpose of operator overloading is to minimize the chances of occurrence of errors in a class that is using the overloaded operators. It also helps in redefining the functionalities of the operators to improve their performance. Operator overloading also makes the program clearer, readable, and more understandable by using common operators, such as +, =, and [].
Specify Some Guidelines That Should Be Followed While Overloading Operators?
Following are some of the guidelines that should be followed while overloading operators
Subscript bracket operators should be used for overloading when there is a need of fetching data from the container class.
Arithmetic operators should be used for providing the numerical calculation to the operators.
Comma operator overloading should be used less often as the ordering properties of this operator vary before and after overloading. This variation in the ordering properties confuses the users of this operator.
The priority order in which operators are executed cannot be modified by overloading the operators.
The overloaded operators must follow the syntax of the language in which they are used.
Explain The Concept Of Friend Function In C++?
The friend function in C++ refers to a class or function that works with the private or protected members of the other class. It gets privileges to access and work with the private members of the other class. The programmer has full control over both the friend and member functions of the class and can use the features of both. The friend function does not require the use of an object and can be invoked without creating the object.
How The Programmer Of A Class Should Decide Whether To Declare Member Function Or A Friend Function?
A programmer should analyze the situations or requirements for deciding whether to declare the member function or friend function for a class. When a function is declared as a friend, the function is able to access all the private and protected member of the class. A member function can be used with encapsulation point of view as friend functions violate the encapsulation and can also access all the private members although they are not a part of the class. From the security point of view, use of member function is safer than the friend function.
Why Should We Use Null Or Zero In A Program?
In C++, <cstdio> header defines NULL, a global symbol that represents a null pointer. NULL has nothing to do with standard input/output except that some functions return a null pointer. C++ programmers do not use the NULL global symbol, preferring to address zero pointer values with the constant integer value 0.
Another problem is that ignoring a 0 return could crash the system when the program tries to assign values through a zero-value pointer.
Write Code That Allows To Create Only One Instance Of A Class?
This is shown in following code snippet.
#include
class sample
{
static sample *ptr ;
private
sample( )
{
}
public
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
} ;
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
Here, the class sample contains a static data member ptr, which is a pointer to the object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available.
Write Code To Add Functions, Which Would Work As Get And Put Properties Of A Class?
This is shown in following code.
#include
class sample
{
int data ;
public
__declspec ( property ( put = fun1, get = fun2 ) )
int x ;
void fun1 ( int i )
{
if ( i < 0 )
data = 0 ;
else
data = i ;
}
int fun2( )
{
return data ;
}
} ;
void main( )
{
sample a ;
a.x = -99 ;
cout << a.x ;
}
Here, the function fun1( ) of class sample is used to set the given integer value into data, whereasfun2( ) returns the current value of data. To set these functions as properties of a class we havegiven the statement as shown below
__declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the value in data. On the other hand, the last statement would cause fun2( ) to get called to return the value of data.
Discuss The Possibilities Related To The Termination Of A Program Before Entering The Mainq Method?
The global variables are initialized dynamically before invoking the main() method. The process of invoking the global variables is slow. If the function is called by initialization of the global variables, then the program is terminated before entering the main() method.
What Is Meant By The Term Name Mangling In C++?
The mangled name includes tokens that identify the function's return type and the types of arguments. Calls to the function and the function definition itself are recorded in the relocatable object file as references to the mangled name, which is unique even though several functions might have the same similar name. Through name mangling, the name of the function is changed into coded and unique names or symbols which can be understand by the user. In this way, the function with the same name can be differentiated with the help of this coded language.
How A Macro Differs From A Template?
A macro defines the meaning for an identifier.The preprocessor replaces macro in the form of strings in the source code with values derived from the macro definition.The most common usage for macros defines a global symbol that represents a value. A macro cannot call itself.
On the contrary, a template allows you to create generic functions that admit any data type as parameters and return a value without having to overload the function with all the possible data types. A template can call itself.
Carry Out Conversion Of One Object Of User-defined Type To Another?
To perform conversion from one user-defined type to another we need to provide conversion function. Following program demonstrates how to provide such conversion function.
class circle
{
private
int radius ;
public
circle ( int r = 0 )
{
radius = r ;
}
} ;
class rectangle
{
private
int length, breadth ;
public
rectangle( int l, int b )
{
length = l ;
breadth = b ;
}
operator circle( )
{
return circle ( length ) ;
}
} ;
void main( )
{
rectangle r ( 20, 10 ) ;
circle c;
c = r ;
}
Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment operator in the class circle which accepts the object of type rectangle. Since there is no such overloaded assignment operator, the conversion operator function that converts the rectangle object to the circle object is searched in the rectangle class. We have provided such a conversion function in the rectangle class. This conversion operator function returns a circle object. By default conversion operators have the name and return type same as the object type to which it converts to. Here the type of the object is circle and hence the name of the operator function as well as the return type is circle.
Write A Program That Implements A Date Class Containing Day, Month And Year As Data Members. Implement Assignment Operator And Copy Constructor In This Class.
This is shown in following program
#include
class date
{
private
int day ;
int month ;
int year ;
public
date ( int d = 0, int m = 0, int y = 0 )
{
day = d ;
month = m ;
year = y ;
}
// copy constructor
date ( date &d )
{
day = d.day ;
month = d.month ;
year = d.year ;
}
// an overloaded assignment operator
date operator = ( date d )
{
day = d.day ;
month = d.month ;
year = d.year ;
return d ;
}
void display( )
{
cout << day << "/" << month << "/" << year ;
}
} ;
void main( )
{
date d1 ( 25, 9, 1979 ) ;
date d2 = d1 ;
date d3 ;
d3 = d2 ;
d3.display( ) ;
}
Write About C++ Storage Classes?
The storage classes are qualifiers that are used to specify the lifetime of a variable. The lifetime of a variable relates to the portion of the program that has access to the variable. Storage class directs the compiler about how to store the variable in memory and how to access variable within the program.
The following are the different types of storage classes
Auto —Identifies the local variable as automatic, which means that each invocation of the statement block in which the variable is defined gets a fresh copy with its own memory space and with re-initialization each time.
Static —Refers that the scope of a static local variable begins inside the statement block in which the variable is declared and ends when the block terminates. The variable itself retains its value between executions of the statement block.
Extern —Declares a global variable in one program that can be accessed by another program. The default value of an extern variable is zero. This variable is useful in a scenario where we divide one large program into different small programs and use external variable in each small program. The main advantage of using external variable is that the complexity of a program can be reduced by separating a large program into smaller programs and using external variable, which is shared by all the programs.
Register —Refers that a variable declared with the register storage class is the same as an auto variable except that the program cannot take the variable's address. Its purpose is to allow the programmer to specify conditions under which the program's performance would be improved if certain local and automatic variables were maintained in one of the computer's hardware registers.
What Are The Advantages Of Using Const Reference Arguments In A Function?
The following are the advantages of using the const reference arguments in a function
a. Protects against errors that result in altering data of a program.
b. Allows the processing of const and non-const actual arguments by the function. On the contrary, in the prototype, the acceptance of only non-constant arguments is done by the function without a const.
c. Allows the generation and usage of a temporary variable by the function appropriately.
What Kind Of Problems Can Be Solved By A Namespace?
The namespace feature is used to avoid the name collision caused due to the use of the global identifiers by multiple providers of libraries. The provider of libraries avoids such name collisions by assigning the unique namespace to the libraries. The namespace feature is a logical space which uniquely identifies a resource, such as a program or class.
The declaration of a namespace is given as follows
namespace[identifier]
{
namespace-body
}
Why Do We Use The Using Declaration?
A using declaration specifies that all the identifiers in the namespace are available to the program within the scope of the using declaration. It makes all the namespace's identifiers available to the program in the context of their own outer scope. The principle use of the using declaration is to support standard library interfaces that are well known.
Write About An Iterator Class?
Iterator class provides an access to the classes which are inside the containers (it holds a group of objects in an organized way). The containers include the data structure, class, and abstract data type. Each container type supports one category of iterator depending on the container's requirements. The categories are input, output, forward, bidirectional, and random access. These properties specify the behavior that the iterator must exhibit in order to support the container. Iterators can be initialized, incremented, and decremented, and their bounds can be limited to the current extent of the containers. If you can cause an iterator to be equal to another iterator by incrementing the first one, the second iterator is reachable from the first. The two iterators are also known to refer to the same container. The two iterators can therefore define a range of objects in the container.
Discuss The Effects Occur, After An Exception Thrown By A Member Function Is Unspecified By An Exception Specification?
When a function throws an exception, not given in the specification, the exception is passed to a system function named unexpected. The unexpected function calls the latest function named as an argument in a call to the set_unexpected function, which returns its current settings. A function with no exception specification, by default, calls the terminate function, which finally calls the abort (function to terminate the program).
How Can I Be Thrown Polymorphically?
The following code can be used to throw i polymorphically
classExceptionParent { );
classE,cceptionChild : public ExceptionParent ( );
void f(ExceptionParent8 e)
/1
throw e;
void go
ExceptionChild e;
try(
fCc);
catch (ExceptionChild& e) (
//...code to handle ExceptlonChild...
catch C...) (
//...code to handle other exceptions...
)
)
In the preceding code, you can enter the catch (...) clause in the absence of throwing i polymorphically. The throw e in the function f () throws the same type of an object as an expression of static type.
What Is The Role Of Copy Constructor In Copying Of Thrown Objects?
A copy constructor with a public access specifier must be applied to the objects which are thrown.With the help of a compiler, the code is generated through which copying of thrown objects can be done. The thrown objects must have a copy constructor with the public access specifier.
How Can An Improvement In The Quality Of Software Be Done By Try/catch/throw?
Error-handling is necessity while developing applications to account for unexpected situations, such as insufficient memory, resource allocation errors, inability to find/open files, division by zero, an arithmetic or array overflow, and the exhaustion of free heap space, which occur at runtime.
Programmers have various styles of dealing with such exceptions, such as try/catch /throw methods, which cause diversity in coding practice. This diversity increases with the use of user-defined classes, as each class brings with it potential class-specific errors. These methods provide a standard facility to deal with runtime exceptions. Moreover, try/catch/throw result in the code with fewer errors. It is low in cost in relation to development. With error-handling, your program can detect unexpected events and recover from them.
Cognizant Frequently Asked C++ Interview Questions Answers |
What Is A Dangling Pointer?
When the location of the deallocated memory is pointed by the pointer even after the deletion or allocation of objects is done, without the modification in the value of the pointer, then this type of pointer is called a dangling pointer.
Explain The Concept Of Memory Leak.
When a variable does not exist longer in the memory, and deletion or reuse of that variable cannot be done, then its destruction occurs automatically. This concept is called memory leak.
For example, consider the following code snippet
{
parent*p=new parent();
}
In the preceding code snippet, the p variable does not exist in the memory, but the variable is not deleted. Therefore, it becomes out of scope and its destruction occurs, which results in memory leak.
List The Issue That The Auto_ptr Object Handles?
The auto_ptr object is used to deallocate memory, which is allocated to a variable, when the variable goes out of scope.
What Are Smart Pointers?
Smart pointers are almost similar to pointers with additional features, such as automatic destruction of a variable when it becomes out of scope and the throwing of exceptions that ensures the proper destruction of the dynamically allocated objects. They are useful in keeping tracks of dynamically allocated objects. Due to these additional capabilities, they reduce the possibilities of occurrence of exceptions and errors in a program and ensure that the written code is safe and efficient.
How A Pointer Differs From A Reference?
A pointer differs from a reference in the following ways
In the case of reference, an object must always be referred while initializing. On the contrary, such restrictions are not meant for pointers.
The different types of objects can be pointed by the pointers by reassigning the pointers with different objects. On the contrary, in a reference, the same object which was initialized earlier can only be referred by a reference.
You can use a null address in a pointer parameter to indicate that a variable does not exist; whereas, there is no existence of a null reference in C++.
A reference usually appears outside an object; whereas, a pointer generally appears inside an object.
How Const Int *ourpointer Differs From Int Const *ourpointer?
As a rule, pointer declarations should be read from right to left. In the pointer declaration, const int *ourPointer, ourPointer is a pointer to a const int object, which cannot be changed by using a pointer. Whereas in case of the int const *ourPointer pointer declaration, ourPointer is a const pointer to an int object, in which an int object can be changed by using a pointer but the pointer itself cannot be changed because it is constant.
Explain How Overloading Takes Place In C++?
C++ supports two types of overloading namely, function overloading and operator overloading. Function overloading helps in defining more than one function with the same name, but with different signatures. An error is raised if two overloaded functions are provided with the same function signature. Operator overloading helps in giving special meanings to operators, when they are used with user-defined classes.
What Is The Difference Between Prefix And Postfix Versions Of Operator++()?
The prefix and postfix versions of operator ++() can be differentiated on the basis of arguments defined. The postfix operator ++() consists of a dummy parameter of int datatype; whereas, a dummy parameter is not found in the prefix operator ++().
Describe The Advantages Of Operator Overloading?
Operator overloading is used to provide some extra features, behaviors, and abilities to the users of a particular class. This feature in C++ helps in controlling the functions performed by an operator and reduces the chance of occurrence of errors in a program.
Provide Some Examples Of Operator Overloading?
The implementation of operator overloading is done in the following ways
Concatenating two std:-.string objects by using the + operator
Incrementing a Date object by using the ++ operator
Multiplying two different number objects by using the * operator
Accessing array elements from an object of the Array class by using the subscript operator
Can The Operator == Be Overloaded For Comparing Two Arrays Consisting Of Characters By Using String Comparison?
The operator == cannot be overloaded to compare two arrays consisting of characters using string comparisons. It should be noted that out of the two operands of an overloaded operator, at least one operand should be of user- defined type. This user-defined type usually refers to a class. Two characters can be compared easily using classes, such as std::string, rather than using an array containing characters.
Can The Creation Of Operator** Is Allowed To Perform The To-the-power-of Operations?
No, you cannot create operator** for to-the-power-of operations. The number of parameters taken by an operator, names of the operators, priority level of the operators, and the associativity of the operators depend on language in which they are being used. The operator** is not present in C++, so it cannot be created.
What Is The Main Purpose Of Overloading Operators?
The main purpose of operator overloading is to minimize the chances of occurrence of errors in a class that is using the overloaded operators. It also helps in redefining the functionalities of the operators to improve their performance. Operator overloading also makes the program clearer, readable, and more understandable by using common operators, such as +, =, and [].
Specify Some Guidelines That Should Be Followed While Overloading Operators?
Following are some of the guidelines that should be followed while overloading operators
Subscript bracket operators should be used for overloading when there is a need of fetching data from the container class.
Arithmetic operators should be used for providing the numerical calculation to the operators.
Comma operator overloading should be used less often as the ordering properties of this operator vary before and after overloading. This variation in the ordering properties confuses the users of this operator.
The priority order in which operators are executed cannot be modified by overloading the operators.
The overloaded operators must follow the syntax of the language in which they are used.
Explain The Concept Of Friend Function In C++?
The friend function in C++ refers to a class or function that works with the private or protected members of the other class. It gets privileges to access and work with the private members of the other class. The programmer has full control over both the friend and member functions of the class and can use the features of both. The friend function does not require the use of an object and can be invoked without creating the object.
How The Programmer Of A Class Should Decide Whether To Declare Member Function Or A Friend Function?
A programmer should analyze the situations or requirements for deciding whether to declare the member function or friend function for a class. When a function is declared as a friend, the function is able to access all the private and protected member of the class. A member function can be used with encapsulation point of view as friend functions violate the encapsulation and can also access all the private members although they are not a part of the class. From the security point of view, use of member function is safer than the friend function.
Why Should We Use Null Or Zero In A Program?
In C++, <cstdio> header defines NULL, a global symbol that represents a null pointer. NULL has nothing to do with standard input/output except that some functions return a null pointer. C++ programmers do not use the NULL global symbol, preferring to address zero pointer values with the constant integer value 0.
Another problem is that ignoring a 0 return could crash the system when the program tries to assign values through a zero-value pointer.
Write Code That Allows To Create Only One Instance Of A Class?
This is shown in following code snippet.
#include
class sample
{
static sample *ptr ;
private
sample( )
{
}
public
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
} ;
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
Here, the class sample contains a static data member ptr, which is a pointer to the object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available.
Write Code To Add Functions, Which Would Work As Get And Put Properties Of A Class?
This is shown in following code.
#include
class sample
{
int data ;
public
__declspec ( property ( put = fun1, get = fun2 ) )
int x ;
void fun1 ( int i )
{
if ( i < 0 )
data = 0 ;
else
data = i ;
}
int fun2( )
{
return data ;
}
} ;
void main( )
{
sample a ;
a.x = -99 ;
cout << a.x ;
}
Here, the function fun1( ) of class sample is used to set the given integer value into data, whereasfun2( ) returns the current value of data. To set these functions as properties of a class we havegiven the statement as shown below
__declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the value in data. On the other hand, the last statement would cause fun2( ) to get called to return the value of data.
The global variables are initialized dynamically before invoking the main() method. The process of invoking the global variables is slow. If the function is called by initialization of the global variables, then the program is terminated before entering the main() method.
What Is Meant By The Term Name Mangling In C++?
The mangled name includes tokens that identify the function's return type and the types of arguments. Calls to the function and the function definition itself are recorded in the relocatable object file as references to the mangled name, which is unique even though several functions might have the same similar name. Through name mangling, the name of the function is changed into coded and unique names or symbols which can be understand by the user. In this way, the function with the same name can be differentiated with the help of this coded language.
How A Macro Differs From A Template?
A macro defines the meaning for an identifier.The preprocessor replaces macro in the form of strings in the source code with values derived from the macro definition.The most common usage for macros defines a global symbol that represents a value. A macro cannot call itself.
On the contrary, a template allows you to create generic functions that admit any data type as parameters and return a value without having to overload the function with all the possible data types. A template can call itself.
Carry Out Conversion Of One Object Of User-defined Type To Another?
To perform conversion from one user-defined type to another we need to provide conversion function. Following program demonstrates how to provide such conversion function.
class circle
{
private
int radius ;
public
circle ( int r = 0 )
{
radius = r ;
}
} ;
class rectangle
{
private
int length, breadth ;
public
rectangle( int l, int b )
{
length = l ;
breadth = b ;
}
operator circle( )
{
return circle ( length ) ;
}
} ;
void main( )
{
rectangle r ( 20, 10 ) ;
circle c;
c = r ;
}
Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment operator in the class circle which accepts the object of type rectangle. Since there is no such overloaded assignment operator, the conversion operator function that converts the rectangle object to the circle object is searched in the rectangle class. We have provided such a conversion function in the rectangle class. This conversion operator function returns a circle object. By default conversion operators have the name and return type same as the object type to which it converts to. Here the type of the object is circle and hence the name of the operator function as well as the return type is circle.
Write A Program That Implements A Date Class Containing Day, Month And Year As Data Members. Implement Assignment Operator And Copy Constructor In This Class.
This is shown in following program
#include
class date
{
private
int day ;
int month ;
int year ;
public
date ( int d = 0, int m = 0, int y = 0 )
{
day = d ;
month = m ;
year = y ;
}
// copy constructor
date ( date &d )
{
day = d.day ;
month = d.month ;
year = d.year ;
}
// an overloaded assignment operator
date operator = ( date d )
{
day = d.day ;
month = d.month ;
year = d.year ;
return d ;
}
void display( )
{
cout << day << "/" << month << "/" << year ;
}
} ;
void main( )
{
date d1 ( 25, 9, 1979 ) ;
date d2 = d1 ;
date d3 ;
d3 = d2 ;
d3.display( ) ;
}
Write About C++ Storage Classes?
The storage classes are qualifiers that are used to specify the lifetime of a variable. The lifetime of a variable relates to the portion of the program that has access to the variable. Storage class directs the compiler about how to store the variable in memory and how to access variable within the program.
The following are the different types of storage classes
Auto —Identifies the local variable as automatic, which means that each invocation of the statement block in which the variable is defined gets a fresh copy with its own memory space and with re-initialization each time.
Static —Refers that the scope of a static local variable begins inside the statement block in which the variable is declared and ends when the block terminates. The variable itself retains its value between executions of the statement block.
Extern —Declares a global variable in one program that can be accessed by another program. The default value of an extern variable is zero. This variable is useful in a scenario where we divide one large program into different small programs and use external variable in each small program. The main advantage of using external variable is that the complexity of a program can be reduced by separating a large program into smaller programs and using external variable, which is shared by all the programs.
Register —Refers that a variable declared with the register storage class is the same as an auto variable except that the program cannot take the variable's address. Its purpose is to allow the programmer to specify conditions under which the program's performance would be improved if certain local and automatic variables were maintained in one of the computer's hardware registers.
What Are The Advantages Of Using Const Reference Arguments In A Function?
The following are the advantages of using the const reference arguments in a function
a. Protects against errors that result in altering data of a program.
b. Allows the processing of const and non-const actual arguments by the function. On the contrary, in the prototype, the acceptance of only non-constant arguments is done by the function without a const.
c. Allows the generation and usage of a temporary variable by the function appropriately.
What Kind Of Problems Can Be Solved By A Namespace?
The namespace feature is used to avoid the name collision caused due to the use of the global identifiers by multiple providers of libraries. The provider of libraries avoids such name collisions by assigning the unique namespace to the libraries. The namespace feature is a logical space which uniquely identifies a resource, such as a program or class.
The declaration of a namespace is given as follows
namespace[identifier]
{
namespace-body
}
Why Do We Use The Using Declaration?
A using declaration specifies that all the identifiers in the namespace are available to the program within the scope of the using declaration. It makes all the namespace's identifiers available to the program in the context of their own outer scope. The principle use of the using declaration is to support standard library interfaces that are well known.
Write About An Iterator Class?
Iterator class provides an access to the classes which are inside the containers (it holds a group of objects in an organized way). The containers include the data structure, class, and abstract data type. Each container type supports one category of iterator depending on the container's requirements. The categories are input, output, forward, bidirectional, and random access. These properties specify the behavior that the iterator must exhibit in order to support the container. Iterators can be initialized, incremented, and decremented, and their bounds can be limited to the current extent of the containers. If you can cause an iterator to be equal to another iterator by incrementing the first one, the second iterator is reachable from the first. The two iterators are also known to refer to the same container. The two iterators can therefore define a range of objects in the container.
Post a Comment