Tuesday, June 16, 2020

C++ Interview Questions and Answers

Question 1. What Is The Difference Between C And C++ ?

Answer :

C is a procedural language on the other hand c++ is an object oriented language.

C follows top down approach, c++ follows bottom up approach.

C is a low level language, c++ is a middle level language.

Input and putput functions differs in the two languages, c uses printf and scanf whereas c++ uses >> and << as input and output operators.

C++ can be broken down to solve real world problems which is not the case in c.

Question 2. What Is The Difference Between Declaration And Definition ?

Answer :

There are basically two differences between declaration and definition : 

In declaration no space is reserved for the variable, declaration only tells about the 'type' of the variable we are using or we will be using int he program.

Definition on the other hand reserves the sapce for the variable and some initial value is given to it.

Another major difference is that redeclaration is not an error whereas redefinition is an error,

In simple words, when we declare no space is reserved for the variable and we can redeclare it in the program

On the other hand, when we define a variable some sapce is reserved for it to hold values plus some initial value is also given to it, apart from it we cannot give another definition to the variable, i.e. we cannot define it again.

Example: 

extern int x -> is a declaration whereas int y is definition.

Question 3. If You Want To Share Several Functions Or Variables In Several Files Maintaining The Consistency How Would You Share It?

Answer :

To maintain the consistency between several files firstly place each definition in '.c' file than using external declarations put it in '.h' file after it is included .h file we can use it in several files using #include as it will be in one of the header files, thus to maintain the consistency we can make our own header file and include it where ever needed.

Question 4. What Do You Mean By Translation Unit?

Answer :

A Translation Unit is a set of source files that is seen by the compiler and it translate it as one unit which is generally.file and all the header files mentioned in #include directives.

When a C preprocessor expands the source file with all the header files the result is the preprocessing translation unit which when further processed translates the preprocessing translation unit into translation unit, further with the help of this translation unit compiler forms the object file and ultimately forms an executable program.

Question 5. Describe Linkages And Types Of Linkages?

Answer :

When we declare identifiers within the same scope or in the different scopes they can be made to refer the same object or function with the help of likages. 

There are three types of linkages: 

External linkage 

Internal linkage 

None linkage

EXternal Linkages means 'global, non-static' functions or variable.

Example: extern int a1

Internal Linkages means static variable and functions. Example: static int a2

None Linkages means local variables.

Example : int a3

Question 6. Keeping In Mind The Efficiency, Which One Between If-else And Switch Is More Efficient?

Answer :

Between if-else chain and switch statements, as far as efficiency is concerned it is hard to say that which one is more efficient because both of them posses hardly any difference in terms of efficiency. 

Switch can ne converted into if else chain internally by the compiler.

Switch statements are compact way of writting a jump table whereas if-else is a long way of writting conditions.

Between if-esle and switch statements, switch cases are prefered to be used in the programming as it is a compact and cleaner way of writting conditions in the program.

Question 7. What Are Structures And Unions?

Answer :

While handling real world problems we come across situations when we want to use different data type as one, C allows the user to define it own data type known as structures and unions.Structures and unions gathers together different atoms of informations that comprise a given entity.

Question 8. What Is The Difference Between Structures And Unions?

Answer :

Conceptually structures and unions are same, the differnce between them lies in their 'Memory Management' or in simple words the memory required by them.

Elements in structures are stored in contiguous blocks, where as in unions the memory is allocated in such a way that the same memory allocated for one variable serves as its memory at one occassion and as memory for another varioable at some other occassion. 

Therefore, the basic difference lies in the way mrmory is allocated to both structures and unions.

Question 9. What Do You Mean By Enumerated Data Type?

Answer :

Enumerated Data type helps the user in defining its own data type and also gives the user an opportunity to define what values this type can take.

The use of Enumerated Data Type maily lie when the program get more complicated or more number of programers are workin on it as it makes the program listings more readable.

Question 10. What Are Preprocessor Directives In C?

Answer :

The Preprocessor processes the source program before it is passed to the compiler. The features that preprocessor offers are known as Prepsocessor Directives.

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name. For example, `#define' is the directive that defnes a macro. Whitespace is also allowed before and after the `#'. A preprocessing directive cannot be more than one line in normal circumstances. Some directive names require arguments.View answers in details

Question 11. How C Functions Prevents Rework And Therefore Saves The Programmers Time As Well As Length Of The Code ?

Answer :

As we know that c allows us to make functions and cal them where ever needed, it prevents rework by calling the same function again and again where ever requires intead for example if we make a funtion that adds two numbers, it can be called anywhere in the program where ever the addintion is needed and we do not need to code again for adding any number. 

It also shortens the length of the program as we do not need to code again the same thing for next time we can simple call the funtion and use it whenever needed.

Question 12. Keyword Mean In Declaration?

Answer :

This keyword indicated that the function or the variable is implemented externally and it emphasizes that the variable ot the function exits external to the file or function.

We use this keyword when we want to make anything global in the project, it does not lie within any function.

Question 13. Can Union Be Self Referenced?

Answer :

No, Union cannot be self referenced because it shares a single memory for all of its data members.View answers in details

Question 14. Define Pointers?

Answer :

Pointes are special type of variables that are used to store the memory address of the other variables.

Pointers are declared normallt as other variables withe diffrence of * that is present in front of the pointer identifier.

There are two operators that are used with the pointers one is '&' and another one is '*'.

& is known as address of operator and * is known as dereferncing operator, both are prefix unary operators.

Question 15. Which Format Specifier Is Used For Printing A Pointer Value?

Answer :

%p is used to display the corresponding argument that is a pointer.

%x can also be used to print values in hexadecimal form.

Question 16. What Is The Use Of 'auto' Keyword ?

Answer :

The auto keyword declares a local variable whose scope remains within the block of code, it is a variable with the local scope.

When we declare a variable with the auto keyword it specify that it belongs to an auto storage class.

These variables are visible only within the bolck in which they are declared.

These types of variables are not initialised automatically instead need to be initialised xplicitly.

Question 17. What Is The Use Of Register Keyword With The Variables?

Answer :

Register keyword signifies that of possible to store variable in the register than store it in register. 

Variables are usually stored in stacks and are passed to and fro to processor whenever required.

Also register keyword when used redused code size which is an important thing in embeded system.

Question 18. What Do You Mean By Global Variables?

Answer :

These are the variables which remains visible throughout the program and are not recreated when they are recalled.

These types are by default initialised to zero and allocated memory on Data Segment.View answers in details

Question 19. What Do You Mean By Static Variables?

Answer :

Static is an access qualifier that limits the scope of the variable but causes the variable to exist for the lifetime of the program. This means a static variable is one that is not seen outside the function in which it is declared as its scopeis limited to the block of code in which it has been created but its lifespan remains until the program terminates.

The value of such a variable will remain and may be seen even after calls to a function also the declaration statement of such type of a variable inside a function is executed only once.

Question 20. What Is The Difference Between Global Variables And Static Variables?

Answer :

The scope of the variable describes that the variable is accessible at certain point in the program or not.

The difference between global variables and static variables lies in this concept only. 

The scope of the global variables remains through out the program also the life span of these variables is through out the program.

The scope of the static Variables remains within the block of code in which they are created but the life span remains through out the program.

Thus, the main difference is between the scope of both type of variables.

Question 21. What Is The Difference Between Global Variables And Local Variable?

Answer :

First, Global variables are the variables which can be accessed from anywhere through out the program whereas local variables are those which can only be accessed within the block of code in which they are created.

Second, global variables are visible throughout the program whereas local variables are not known to the other functions in the programs i.e. they are visible within the block of code in which they are created.

Third, global variables are allocated memory on Data Segament whereas local variables are allocated memory on the stack.

Question 22. What Do You Mean By Volatile Variable?

Answer :

Variables prefixed with the keyword volatile acts as a data type qualifier. The volatile keyword attempts to alter the default way in which the variables are stored and the way the compiler handles the variables.

It is a kind of instruction to the optimizer to not to optimize the varabli during compilation.

Question 23. What Is The Prototype Of Printf Function?

Answer :

Prototype of printf function is:

int printf( const char *format ,?)

In this the Second parameter: '?' (Three continuous dots) are known as called ellipsis which indicates the variable number of arguments.

Question 24. Define Macro?

Answer :

Macros are the identifiers that represent statements or expressions in other words macros are fragment of code which is been given a name. #define directive is used to dedine a macro.

Example, we have define a macro i.e SQUARE(x) x*x. 

Here the macro determines the square of the given number. Macro Declaration: #define name text.

Question 25. What Is The Disadvantage Of Using A Macro?

Answer :

The major disadvantage associated with the macro is :

When a macro is invoked no type checking is performed.Therefore it is important to declare a macro coreectly so that it gives a correct answer whenever it is called inside the program.

Question 26. What Is A Void Pointer?

Answer :

When we declare a variable as a pointer to a variable of type void, it is known as void pointer. Another name for it is generic pointer.

In general we cannot have a void type variable,but if the variable is of void type it do not point to any data and due to this it cannot be de-referenced.

Question 27. What Is A Unnitialised Pointer?

Answer :

When we create a pointer the memory to the pointer is allocated but the contents or value that memory has to hold remains untouched. Unitialised pointers are those pointers which do not hold any initial value.

Example: int *p; is said to be an unitialise pointer, it is recomended to initialise the pointer before actually using it as it an error.

Question 28. What Is Dangling Pointer?

Answer :

These are the pointers that do not point to any object of appropriate type. These are special cases of memory vialation as they do not point to any appropraite type.These arises when some object is deleted from the memory or when an object is deallocated thus the pointer keeps on pointin to the memory location untill it is modified. Dangling pointers may lead to unpredictable results.

Question 29. What Do You Know About Near, Far And Huge Pointer?

Answer :

A near pointer is a 16 bit pointer to an object which is contained in the current segment like code segment, data segment, stack segment and extra segment. It holds only offset address.

A far pointer is a 32 bit pointer to an object anywhere in memory. It can only be used when the compiler allocates a segment register, or we can say the compiler must allocate segment register to use far pointers. These pointers hold 16 bit segment and 16 bit offset address.

Huge pointers are also far pointers i.e. 32 bit pointer the difference is that the huge pointer can be increased or decreased uniformly between any segments and can have any value from 0 to 1MB.

Question 30. What Is Null Pointer?

Answer :

NULL pointer is not the unitialised pointer that can point anywhere, the NULL pointers are the one which do not point anywhere that is which do not point to any object or any function.

Question 1. Write A Program That Will Convert An Integer Pointer To An Integer And Vice-versa.

Answer :

The following program demonstrates this.

#include<stdio.h>

#include<iosream>

#include<conio.h>

void main( )

{

int i = 65000 ;

int *iptr = reinterpret_cast ( i ) ;

cout << endl << iptr ;

iptr++ ;

cout << endl << iptr ;

i = reinterpret_cast ( iptr ) ;

cout << endl << i ;

i++ ;

cout << endl << i ;

}

Question 2. What Is Meant By Const_cast?

Answer :

The const_cast is used to convert a const to a non-const. This is shown in the following program:

#include

void main( )

{

const int a = 0  ;

int *ptr = ( int * ) &a ; //one way

ptr = const_cast_ ( &a ) ; //better way

}

Here, the address of the const variable a is assigned to the pointer to a non-const variable. The const_cast is also used when we want to change the data members of a class inside the const member functions. The following code snippet shows this:

class sample

{

private:

int data;

public: 

void func( ) const

{

(const_cast (this))->data = 70 ;

}

};

Question 3. What Is Meant By Forward Referencing And When Should It Be Used?

Answer :

Forward referencing is generally required when we make a class or a function as a friend.Consider following program:

class test

{

public:

friend void fun ( sample, test ) ;

} ;

class sample

{

public:

friend void fun ( sample, test ) ;

} ;

void fun ( sample s, test t )

{

// code

}

void main( )

{

sample s ;

test t ;

fun ( s, t ) ;

}

On compiling this program it gives error on the following statement of test class. It gives an error that sample is undeclared identifier. friend void fun ( sample, test ) ; This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample.

class sample;

Question 4. Write My Own Zero-argument Manipulator That Should Work Same As Hex?

Answer :This is shown in following program.

#include

ostream& myhex ( ostream &o )

{

o.setf ( ios::hex) ;

return o ;

}

void main( )

{

cout << endl << myhex << 2000 ;

}

Question 5. We All Know That A Const Variable Needs To Be Initialized At The Time Of Declaration. Then How Come The Program Given Below Runs Properly Even When We Have Not Initialized P?

#include<iostream>

Void Main( )

{

      Const Char *p ;

      P = "a Const Pointer" ;

      Cout << P ;

}

Answer :

The output of the above program is 'A const pointer'. This is because in this program p is declared as 'const char*' which means that value stored at p will be constant and not p and so the program works properly.

Question 6. Refer To A Name Of Class Or Function That Is Defined Within A Namespace?

Answer :There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator through the using keyword. This is shown in following example:

namespace name1

{

class sample1

{

// code

} ;

}

namespace name2

{

class sample2

{

// code

} ;

}

using namespace name2 ;

void main( )

{

name1::sample1 s1 ;

sample2 s2 ;

}

Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers.

Question 7. Is It Possible To Provide Default Values While Overloading A Binary Operator?

Answer :No!. This is because even if we provide the default arguments to the parameters of the overloaded operator function we would end up using the binary operator incorrectly. This is explained in the following example:

sample operator + ( sample a, sample b = sample (2, 3.5f ) )

{

void main( )

{

sample s1, s2, s3 ;

s3 = s1 + ; // error

}

 

 Question 8. Carry Out Conversion Of One Object Of User-defined Type To Another?

Answer :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.

Question 9. Write Code That Allows To Create Only One Instance Of A Class?

Answer :

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.

Question 10. Write Code To Add Functions, Which Would Work As Get And Put Properties Of A Class?

Answer :

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.

Question 11. 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.

Answer :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( ) ;

}

Question 12. When Should I Use Unitbuf Flag?

Answer :

The unit buffering (unitbuf) flag should be turned on when we want to ensure that each character is output as soon as it is inserted into an output stream. The same can be done using unbuffered output but unit buffering provides a better performance than the unbuffered output.

Question 13. What Are Manipulators?

Answer :

Manipulators are the instructions to the output stream to modify the output in various ways. The manipulators provide a clean and easy way for formatted output in comparison to the formatting flags of the ios class. When manipulators are used, the formatting instructions are inserted directly into the stream. Manipulators are of two types, those that take an argument and those that don't.

Question 14. Differentiate Between The Manipulator And Setf( ) Function?

Answer :

The difference between the manipulator and setf( ) function are as follows:

The setf( ) function is used to set the flags of the ios but manipulators directly insert the formatting instructions into the stream. We can create user-defined manipulators but setf( ) function uses data members of ios class only. The flags put on through the setf( ) function can be put off through unsetf( ) function. Such flexibility is not available with manipulators.

Question 15. How To Get The Current Position Of The File Pointer?

Answer :

We can get the current position of the file pointer by using the tellp( ) member function of ostream class or tellg( ) member function of istream class. These functions return (in bytes) positions of put pointer and get pointer respectively.

Question 16. What Are Put And Get Pointers?

Answer :

These are the long integers associated with the streams. The value present in the put pointer specifies the byte number in the file from where next write would take place in the file. The get pointer specifies the byte number in the file from where the next reading should take place.

Question 17. What Does The Nocreate And Noreplace Flag Ensure When They Are Used For Opening A File?

Answer :

nocreate and noreplace are file-opening modes. A bit in the ios class defines these modes. The flag nocreate ensures that the file must exist before opening it. On the other hand the flag noreplace ensures that while opening a file for output it does not get overwritten with new one unless ate or app is set. When the app flag is set then whatever we write gets appended to the existing file. When ate flag is set we can start reading or writing at the end of existing file.

Question 18. What Is The Limitation Of Cin While Taking Input For Character Array?

Answer :

To understand this consider following statements,

char str[5] ;

cin >> str ;

While entering the value for str if we enter more than 5 characters then there is no provision in cin to check the array bounds. If the array overflows, it may be dangerous. This can be avoided by using get( ) function. For example, consider following statement,cin.get ( str, 5 ) ; On executing this statement if we enter more than 5 characters, then get( ) takes only first five characters and ignores rest of the characters. Some more variations of get( ) are available, such as shown below:

get ( ch ) - Extracts one character only get ( str, n ) - Extracts up to n characters into str get ( str, DELIM ) - Extracts characters into array str until specified delimiter (such as '\n'). Leaves delimiting character in stream.

get ( str, n, DELIM ) - Extracts characters into array str until n characters or DELIM character, leaving delimiting character in stream.

Question 19. Mention The Purpose Of Istream Class?

Answer :

The istream class performs activities specific to input. It is derived from the iosclass. The most commonly used member function of this class is the overloaded >> operator which canextract values of all basic types. We can extract even a string using this operator.

Question 20. Would The Following Code Work?

 #include<iosteram.>

Void Main( )

 {

 Ostream O ;

 O << "dream. Then Make It Happen!" ;

}

Answer :

No This is because we cannot create an object of the iostream class since its constructor and copy constructorare declared private.

Question 21. Can We Use This Pointer Inside Static Member Function?

Answer :

No! The this pointer cannot be used inside a static member function. This is because a static member function is never called through an object.

Question 22. What Is Strstream?

Answer :

strstream is a type of input/output stream that works with the memory. It allows using section of the memory as a stream object. These streams provide the classes that can be used for storing the stream of bytes into memory. For example, we can store integers, floats and strings as a stream of bytes. There are several classes that implement this in-memory formatting. The class ostrstream derived from ostream is used when output is to be sent to memory, the class istrstream derived from istream is used when input is taken from memory and strstream class derived from iostream is used for memory objects that do both input and output.

Question 23. When The Constructor Of A Base Class Calls A Virtual Function, Why Doesn't The Override Function Of The Derived Class Gets Called?

Answer :

While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class would get called. This is illustrated in the following example.

#include

class base

{

protected :

int i ;

public :

base ( int ii = 0 )

{

i = ii ;

show( ) ;

}

 

virtual void show( )

{

cout << "base's show( )" << endl ;

}

} ;

 

class derived : public base

{

private :

int j ;

public :

derived ( int ii, int jj = 0 ) : base ( ii )

{

j = jj ;

show( ) ;

}

void show( )

{

cout << "derived's show( )" << endl ;

}

} ;

 

void main( )

{

derived dobj ( 20, 5 ) ;

}

The output of this program would be:

base's show( )

derived's show(

Question 24. Can I Have A Reference As A Data Member Of A Class? If Yes, Then How Do I Initialise It?

Answer :Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialised in the initialisation list of the constructor. This is shown in following program.

#include

class sample

{

private :

int& i ;

public :

sample ( int& ii ) : i ( ii )

{

}

void show( )

{

cout << i << endl ;

}

} ;

 

void main( )

{

int j = 10 ;

sample s ( j ) ;

s.show( ) ;

}

Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference.

Question 25. Why Does The Following Code Fail?

#include<iostream.>

#include<string.h>

Class Sample

{

Private :char *str ;

Public : Sample ( Char *s )

{

Strcpy ( Str, S ) ;

}

~sample( )

{

Delete Str ;

}

} ;

Void Main( )

{

Sample S1 ( "abc" ) ;

}

Answer :

Here, through the destructor we are trying to deal locate memory, which has been allocated statically. To remove an exception, add following statement to the constructor.

sample ( char *s )

{

str = new char[strlen(s) + 1] ;

strcpy ( str, s ) ;

}

Here, first we have allocated memory of required size, which then would get deal located through the destructor.

Question 26. Assert( ) Macro...

Answer :We can use a macro called assert( ) to test for conditions that should not occur in a code. This macro expands to an if statement. If test evaluates to 0, assert prints an error message and calls abort to abort the program.

#include

#include

void main( )

{

int i ;

cout << "\nEnter an integer: " ;

cin >> i ;

assert ( i >= 0 ) ;

cout << i << endl ;

}

Question 27. Why Is That Unsafe To Deal Locate The Memory Using Free( ) If It Has Been Allocated Using New?

Answer :This can be explained with the following example:

#include

class sample

{

int *p ;

public :

sample( )

{

p = new int ;

}

 

~sample( )

{

delete p ;

}

} ;

 

void main( )

{

sample *s1 = new sample ;

free ( s1 ) ;

sample *s2 = ( sample * ) malloc ( sizeof ( sample ) ) ;

delete s2 ;

}

The new operator allocates memory and calls the constructor. In the constructor we have allocated memory on heap, which is pointed to by p. If we release the object using the free( ) function the object would die but the memory allocated in the constructor would leak. This is because free( ) being a C library function does not call the destructor where we have deal located the memory.

As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error.

Question 28. Can We Distribute Function Templates And Class Templates In Object Libraries?

Answer :

No! We can compile a function template or a class template into object code (.obj file). The code that contains a call to the function template or the code that creates an object from a class template can get compiled. This is because the compiler merely checks whether the call matches the declaration (in case of function template) and whether the object definition matches class declaration (in case of class template). Since the function template and the class template definitions are not found, the compiler leaves it to the linker to restore this. However, during linking, linker doesn't find the matching definitions for the function call or a matching definition for object creation. In short the expanded versions of templates are not found in the object library. Hence the linker reports error.

Question 29. Differentiate Between An Inspector And A Mutator ?

Answer :An inspector is a member function that returns information about an object's state (information stored in object's data members) without changing the object's state. A mutator is a member function that changes the state of an object. In the class Stack given below we have defined a mutator and an inspector.

class Stack

{

public :

int pop( ) ;

int getcount( ) ;

}

In the above example, the function pop( ) removes top element of stack thereby changing the state of an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector because it simply counts the number of elements in the stack without changing the stack.

Question 30. Namespaces:

Answer :The C++ language provides a single global namespace. This can cause problems with global name clashes. For instance, consider these two C++ header files: // file1.h float f ( float, int ) ; class sample { ... } ; // file2.h class sample { ... } ; With these definitions, it is impossible to use both header files in a single program; the sample classes will clash.A namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier thus avoids the possibility that a name will conflict with names declared elsewhere in the program. It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier. For example:

// file1.h

namespace file1

{

float f ( float, int ) ;

class sample { ... } ;

}

// file2.h

namespace file2

{

class sample { ... } ;

}

Now the class names will not clash because they become file1::sample and file2::sample, respectively.

Question 31. Declare A Static Function As Virtual?no. The Virtual Function Mechanism Is Used On The Specific Object That Determines Which Virtual Function To Call. Since The Static Functions Are Not Any Way Related To Objects, They Cannot Be Declared As Virtual.

Answer :

No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects, they cannot be declared as virtual.

Question 32. Can User-defined Object Be Declared As Static Data Member Of Another Class?

Answer :Yes. The following code shows how to initialize a user-defined object.

#include

class test

{

int i ; 

public :

test ( int ii = 0 )

{

i = ii ; 

}

} ;

class sample

{

static test s ;

} ;

test sample::s ( 26 ) ;

Here we have initialized the object s by calling the one-argument constructor. We can use the same convention to initialize the object by calling multiple-argument constructor.

Question 33. What Is A Forward Referencing And When Should It Be Used?

Answer :Consider the following program:

class test

{

public :

friend void fun ( sample, test ) ; 

} ;

 

class sample

{

public :

friend void fun ( sample, test ) ;

} ;

 

void fun ( sample s, test t )

{

// code 

}

 

void main( )

{

sample s ;

test t ;

fun ( s, t ) ;

}

This program would not compile. It gives an error that sample is undeclared identifier in the statement friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample. Forward referencing is generally required when we make a class or a function as a friend.

Question 34. What Is Virtual Multiple Inheritance?

Answer :A class b is defined having member variable i. Suppose two classes d1 and d2 are derived from class b and a class multiple is derived from both d1 and d2. If variable i is accessed from a member function of multiple then it gives error as 'member is ambiguous'. To avoid this error derive classes d1 and d2 with modifier virtual as shown in the following program.

#include

class b

{

public :

int i ;

public :

fun( )

{

i = 0 ;

}

} ;

class d1 : virtual public b

{

public :

fun( )

{

i = 1 ;

}

} ;

class d2 : virtual public b

{

public :

fun( )

{

i = 2 ;

}

} ;

class multiple : public d1, public d2

{

public :

fun( )

{

i = 10 ;

}

} ;

void main( )

{

multiple d ;

d.fun( ) ;

cout << d.i ;

}

Question 35. Can We Use This Pointer In A Class Specific, Operator-overloading Function For New Operator?

Answer :

No! The this pointer is never passed to the overloaded operator new() member function because this function gets called before the object is created. Hence there is no question of the this pointer getting passed to operator new( ).

Question 36. How To Allocate Memory Dynamically For A Reference?

Answer :

No! It is not possible to allocate memory dynamically for a reference. This is because, when we create a reference, it gets tied with some variable of its type. Now, if we try to allocate memory dynamically for a reference, it is not possible to mention that to which variable the reference would get tied.

Question 37. Write Code To Make An Object Work Like A 2-d Array?

Answer :Take a look at the following program.

#include

class emp

{

public :

int a[3][3] ;

emp( )

{

int c = 1 ;

for ( int i = 0 ; i <= 2 ; i++ )

{

for ( int j = 0 ; j <= 2 ; j++ )

{

a[i][j] = c ;

c++ ;

}

}

}

int* operator[] ( int i )

{

return a[i] ;

}

} ;

void main( )

{

emp e ;

cout << e[0][1] ;

}

The class emp has an overloaded operator [ ] function. It takes one argument an integer representing an array index and returns an int pointer. The statement cout << e[0][1] ; would get converted into a call to the overloaded [ ] function as e.operator[ ] ( 0 ). 0 would get collected in i. The function would return a[i] that represents the base address of the zeroeth row. Next the statement would get expanded as base address of zeroeth row[1] that can be further expanded as *( base address + 1 ). This gives us a value in zeroth row and first column.

Question 38. What Are Formatting Flags In Ios Class?

Answer :The ios class contains formatting flags that help users to format the stream data. Formatting flags are a set of enum definitions. There are two types of formatting flags:On/Off flagsFlags that work in-group The On/Off flags are turned on using the setf( ) function and are turned off using the unsetf( )function. To set the On/Off flags, the one argument setf( ) function is used. The flags working in groups are set through the two-argument setf( ) function. For example, to left justify a string we can set the flag as,

cout.setf ( ios::left );

cout << "KICIT Nagpur";

To remove the left justification for subsequent output we can say,

cout.unsetf ( ios::left );

The flags that can be set/unset include skipws, showbase, showpoint, uppercase, showpos, unitbufand stdio. The flags that work in a group can have only one of these flags set at a time.

Question 39. What Is The Purpose Of Ios::basefield In The Following Statement?

cout.setf ( Ios::hex, Ios::basefield );

Answer :

This is an example of formatting flags that work in a group. There is a flag for each numbering system (base) like decimal, octal and hexadecimal. Collectively, these flags are referred to as basefield and are specified by ios::basefield flag. We can have only one of these flags on at a time. If we set the hex flag as setf ( ios::hex ) then we will set the hex bit but we won't clear the dec bit resulting in undefined behavior. The solution is to call setf( ) as setf ( ios::hex, ios::basefield ). This call first clears all the bits and then sets the hex bit.

Question 40. Can We Get The Value Of Ios Format Flags?

Answer :

Yes! The ios::flags( ) member function gives the value format flags. This function takes no arguments and returns a long ( typedefed to fmtflags) that contains the current format flags.

Question 41. Is There Any Function That Can Skip Certain Number Of Characters Present In The Input Stream?

Answer :

Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown below:

istream& ignore ( int n = 1, int d =EOF );

Sometimes it happens that some extra characters are left in the input stream while taking the input such as, the '\n' (Enter) character. This extra character is then passed to the next input and may pose problem.

To get rid of such extra characters the cin::ignore( ) function is used. This is equivalent to fflush ( stdin ) used in C language. This function ignores the first n characters (if present) in the input stream, stops if delimiter d is encountered.

Question 42. When Should Overload New Operator On A Global Basis Or A Class Basis?

Answer :We overload operator new in our program, when we want to initialize a data item or a class object at the same place where it has been allocated memory. The following example shows how to overload new operator on global basis.

#include

#include

void * operator new ( size_t s )

{

void *q = malloc ( s ) ;

return q ;

}

void main( )

{

int *p = new int ;

*p = 25 ;

cout << *p ;

}

When the operator new is overloaded on global basis it becomes impossible to initialize the data members of a class as different classes may have different types of data members. The following example shows how to overload new operator on class-by-class basis.

#include

#include

class sample

{

int i ;

public :

void* operator new ( size_t s, int ii )

{

sample *q = ( sample * ) malloc ( s ) ;

q -> i = ii ;

return q ;

}

} ;

class sample1

{

float f ; 

public :

void* operator new ( size_t s, float ff )

{

sample1 *q = ( sample1 * ) malloc ( s ) ;

q -> f = ff ;

return q ;

}

} ;

void main( )

{

sample *s = new ( 7 ) sample ;

sample1 *s1 = new ( 5.6f ) sample1 ;

}

Overloading the operator new on class-by-class basis makes it possible to allocate memory for an object and initialize its data members at the same place.

Question 43. How To Give An Alternate Name To A Namespace?

Answer :

An alternate name given to namespace is called a namespace-alias. namespace-alias is generally used to save the typing effort when the names of namespaces are very long or complex. The following syntax is used to give an alias to a namespace.

namespace myname = my_old_very_long_name ;

Question 44. Define A Pointer To A Data Member Of The Type Pointer To Pointer?

Answer :The following program demonstrates this...

#include

class sample

{

public :

sample ( int **pp )

{

p = pp ;

}

int **p ;

} ;

int **sample::*ptr = &sample::p ;

void main( )

{

int i = 9 ;

int *pi = &i ;

sample s ( π ) ;

cout << ** ( s.*ptr ) ;

}

Question 45. Using A Smart Pointer Can We Iterate Through A Container?

Answer :Yes. A container is a collection of elements or objects. It helps to properly organize and store the data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate through a container using a smart pointer.

#include

class smartpointer

{

private :

int *p ; // ordinary pointer

public :

smartpointer ( int n )

{

p = new int [ n ] ;

int *t = p ;

for ( int i = 0 ; i <= 9 ; i++ )

*t++ = i * i ;

}

int* operator ++ ( int )

{

return p++ ;

}

int operator * ( )

{

return *p ;

}

} ;

void main( )

{

smartpointer sp ( 10 ) ;

for ( int i = 0 ; i <= 9 ; i++ )

cout << *sp++ << endl ;

}

Here, sp is a smart pointer. When we say *sp, the operator * ( ) function gets called. It returns the integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to the next element in the array and then returns the address of this new location.

Question 46. Is It Possible For The Objects To Read And Write Themselves?

Answer :Yes! This can be explained with the help of following example:

#include

#include

class employee

{

private :

char name [ 20 ] ;

int age ;

float salary ;

public :

void getdata( )

{

cout << "Enter name, age and salary of employee : " ;

cin >> name >> age >> salary ;

}

void store( )

{

ofstream file ;

file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ;

file.write ( ( char * ) this, sizeof ( *this ) ) ;

file.close( ) ;

}

void retrieve ( int n )

{

ifstream file ;

file.open ( "EMPLOYEE.DAT", ios::binary ) ;

file.seekg ( n * sizeof ( employee ) ) ;

file.read ( ( char * ) this, sizeof ( *this ) ) ;

file.close( ) ;

}

void show( )

{

cout << "Name : " << name

<< endl << "Age : " << age

<< endl << "Salary :" << salary << endl ;

}

} ;

void main( )

{

employee e [ 5 ] ;

for ( int i = 0 ; i <= 4 ; i++ )

{

e [ i ].getdata( ) ;

e [ i ].store( ) ;

}

for ( i = 0 ; i <= 4 ; i++ )

{

e [ i ].retrieve ( i ) ;

e [ i ].show( ) ;

}

}

Here, employee is the class whose objects can write and read themselves. The getdata( ) function has been used to get the data of employee and store it in the data members name, age and salary. The store( ) function is used to write an object to the file. In this function a file has been opened in append mode and each time data of current object has been stored after the last record (if any) in the file.Function retrieve( ) is used to get the data of a particular employee from the file. This retrieved data has been stored in the data members name, age and salary. Here this has been used to store data since it contains the address of the current object. The function show( ) has been used to display the data of employee.

Question 47. Why Is It Necessary To Use A Reference In The Argument To The Copy Constructor?

Answer :

If we pass the copy constructor the argument by value, its copy would get constructed using the copy constructor. This means the copy constructor would call itself to make this copy. This process would go on and on until the compiler runs out of memory. This can be explained with the help of following example:

class sample

{

int i ;

public :

sample ( sample p )

{

i = p.i ;

}

} ;

void main( )

{

sample s ;

sample s1 ( s ) ;

}

While executing the statement sample s1 ( s ), the copy constructor would get called. As the copy construct here accepts a value, the value of s would be passed which would get collected in p. We can think of this statement as sample p = s. Here p is getting created and initialized. Means again the copy constructor would get called. This would result into recursive calls. Hence we must use a reference as an argument in a copy constructor.

Question 48. What Is C++?

Answer :

Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory management and adding several features - including a new datatype known as a class (you will learn more about these later) - to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.

C++ used for:

C++ is a powerful general-purpose programming language. It can be used to create small programs or large applications. It can be used to make CGI scripts or console-only DOS programs. C++ allows you to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++.

Question 49. What Is A Modifier In C++?

Answer :

A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as 'mutators'. Example: The function mod is a modifier in the following code snippet:

class test

{

int  x,y;

public:

test()

{

x=0; y=0;

}

void mod()

{  x=10;

y=15; 

}

};

Question 50. What Is An Accessor In C++?

Answer :

An accessor is a class operation that does not modify the state of an object in C++. The accessor functions need to be declared as const operations.

Question 51. Differentiate Between A Template Class And Class Template In C++?

Answer :

Template class:  A generic definition or a parameterized class not instantiated until the client provides the needed information. It's jargon for plain templates.

Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It's jargon for plain classes.

Question 52. When Does A Name Clash Occur In C++?

Answer :

A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.

Question 53. Define Namespace In C++?

Answer :

It is a feature in C++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.

Question 54. What Is The Use Of 'using' Declaration In C++?

Answer :

A using declaration in C++ makes it possible to use a name from a namespace without the scope operator.

Question 55. What Is An Iterator Class In C++?

Answer :

A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. The simplest and safest iterators are those that permit read-only access to the contents of a container class.

Question 56. What Is An Incomplete Type In C++?

Answer :

Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification.

int *i=0x400    //i points to address 400

*i=0;          //set the  value of memory location pointed by i.

Incomplete types are otherwise called uninitialized pointers.

Question 57. What Is A Dangling Pointer In C++?

Answer :

A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed. The following code snippet shows this:

class Sample

{

public:int *ptr; Sample(int i)

{

ptr = new  int(i);

}

~Sample()

{

delete ptr;

}

void PrintValO

{

cout« "The value is " « *ptr;

}

};

void SomeFunc(Sample  x)

{

cout« "Say i am in someFunc " « endl;

}

int main()

{

Sample si = 10;

SomeFunc(sl);

sl.PrintVal();

}

In the above example when PrintVal() function is called it is called by the pointer that has been freed by the destructor in SomeFunc.

Question 58. Differentiate Between The Message And Method In C++?

Answer :

Message in C++ :

Objects communicate by sending messages to each other.

A message is sent to invoke a method in C++.

Method in C++ :

Provides response to a message.

It is an implementation of an operation in C++.

Question 59. What Is An Adaptor Class Or Wrapper Class In C++?

Answer :

A class that has no functionality of its own is an Adaptor class in C++. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non-object-oriented implementation.

Question 60. What Is A Null Object In C++?

Answer :

It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

Question 61. What Is Class Invariant In C++?

Answer :

A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

Question 62. What Do You Mean By Stack Unwinding In C++?

Answer :

Stack unwinding in C++ is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.

Question 63. Define Pre-condition And Post-condition To A Member Function In C++?

Answer :

Precondition: A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold. For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.

Post-condition: A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false. For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.

Question 64. What Are The Conditions That Have To Be Met For A Condition To Be An Invariant Of The Class?

Answer :

The condition should hold at the end of every constructor.

The condition should hold at the end of every mutator (non-const) operation.

Question 65. What Are Proxy Objects In C++?

Answer :

Objects that stand for other objects are called proxy objects or surrogates.

template <class t=""> class Array2D

{

public:

class Array ID

{

public:

T&operator[](int index);

const T&operator[](int index)const;

};

Array ID operator[] (int index);

const Array ID operator[] (int index) const;

};

The following then becomes legal:

Array2D<float>data(l0,20); cout«data[3][6]; // fine

Here data[3] yields an ArraylD object and the operator [] invocation on that object yields the float in position(3,6) of the original two dimensional array. Clients of the Array 2D class need not be aware of the presence of the ArraylD class. Objects of this latter class stand for one-dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients program as if they were using real, live, two-dimensional arrays. Each ArraylD object stands for a one-dimensional array that is absent from a conceptual model used by the clients of Array2D. In the above example, ArraylD is a proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not exist.

Question 66. Name Some Pure Object Oriented Languages?

Answer :

pure object oriented languages are Smalltalk, Java, Eiffel, Sather.

Question 67. What Is A Node Class In C++?

Answer :

A node class is a class that,

relies on the base class for services and implementation.

provides a wider interface to the users than its base class.

relies primarily on virtual functions in its public interface.

depends on all its direct and indirect base class.

can be understood only in the context of the base class.

can be used as base for further derivation.

can be used to create objects.

A node class is a class that has added new services or functionality beyond the services inherited from its base class.

Question 68. What Is An Orthogonal Base Class In C++?

Answer :

If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

Question 69. What Is A Container Class? What Are The Types Of Container Classes In C++?

Answer :

A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

Question 70. How Do You Write A Function That Can Reverse A Linked-list In C++?

Answer :

void reverselist(void)

{  if(head==0)

return;

if(head-<next==0)

return;

if(head-<next==tail)

{

head-<next = 0;

tail-<next =  head;

}  else

{

node* pre = head;

node* cur = head-<next;

node* curnext = cur-<next; head-<next =  0; cur-<next = head;

for(; curnext !=0;)

{

cur-<next = pre;

pre = cur;

cur = curnext;

curnext = curnext-<next;

}

curnext-<next = cur;

}

}

Question 71. What Is Polymorphism In C++?

Answer :

Polymorphism in C++ is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

Question 72. How Do You Find Out If A Linked-list Has An End? (i.e. The List Is Not A Cycle)

Answer :

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

Question 73. How Can You Tell What Shell You Are Running On Unix System?

Answer :

You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -1 and look for the shell with the highest P(K).

Question 74. What Is Boyce Codd Normal Form?

Answer :

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds:

a->b is a trivial functional dependency (b is a subset of a).

a is a superkey for schema R.

Question 75. What Is Pure Virtual Function?

Answer :

A class is made abstract by declaring one or more of its virtual functions to be pure. A pure virtual function is one with an initializer of = 0 in its declaration.

Question 76. Write A Struct Time Where Integer M, H, S Are Its Members

Answer :

struct Time

{

int m;

int h;

int s;

};

Question 77. How Do You Traverse A Btree In Backward In-order?

Answer :

Process the node in the right subtree.

Process the root.

Process the node in the left subtree.

Question 78. What Is The Two Main Roles Of Operating System?

Answer :

As a resource manager.

As a virtual machine.

Question 79. In The Derived Class, Which Data Member Of The Base Class Are Visible?

Answer :

In the public and protected sections.

Question 80. What Is The Difference Between Realloc() And Free()?

Answer :

The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur.

The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

Question 81. What Is Function Overloading And Operator Overloading?

Answer :

Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

Question 82. What Is The Difference Between Declaration And Definition?

Answer :

The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.

E.g.:

void stars () // declarator

{

for(intj=10;j > =0;j—) //function body

cout«*;

cout« endl; }

Question 83. What Are The Advantages Of Inheritance In C++?

Answer :

It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.

Question 84. How Do You Write A Function That Can Reverse A Linked-list?

Answer :

void reverselist(void)

{

if(head==0)

return;

if(head->next==0)

return;

if(head->next==tail)

{

head->next = 0;

tail->next = head;

}  else

{

node* pre = head;

node* cur = head->next;

node* curnext = cur->next;

head->next = 0; cur-> next = head;

for(; curnext !=0;)

{

cur->next  = pre;

pre  = cur;

cur  = curnext;

curnext = curnext->next;

}

curnext->next = cur;

}

}

Question 85. What Do You Mean By Inline Function?

Answer :

The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

Question 86. Write A Program That Ask For User Input From 5 To 9 Then Calculate The Average?

Answer :

#include  &quot;iostream.h&quot; intmain()

{

intMAX = 4;

int total = 0;

int average; int  numb;

for  (int i=0; KMAX; i++) {

cout«

&quot;Please  enter your input between 5 and 9: &quot;;

cin  » numb;

while  (numb&lt;5 || numb&gt;9) {

cout« &quot;Invalid input, please re-enter: &quot;;

cin  » numb;

}

total = total + numb;

}

average  = total/MAX;

cout« &quot;The average number is: &quot;

« average « &quot;n&quot;;

return 0;

}

Question 87. Write A Short Code Using C++ To Print Out All Odd Number From 1 To 100 Using A For Loop

Answer :

for( unsigned int i = 1; i < = 100; i++ )

if( l & 0x00000001 )

cout«i«",";

Question 88. What Is Public, Protected, Private In C++?

Answer :

Public, protected and private are three access specifiers in C++.

Public data members and member functions are accessible outside the class.

Protected data members and member functions are only available to derived classes.

Private data members and member functions can't be accessed outside the class. However there is an exception can be using friend classes.

Question 89. Write A Function That Swaps The Values Of Two Integers, Using Int* As The Argument Type?

Answer :

void swap(int* a, int*b)

{

intt;

t=*a;

*a = *b;

*b = t;

}

Question 90. What Is Virtual Constructors/destructors?

Answer :

Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object. There is a simple solution to this problem declare a virtual base-class destructor.

This makes all derived-class destructors virtual even though they don't have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

Question 91. What Is The Difference Between An Array And A List?

Answer :

Array:  is collection of homogeneous elements.

List :is collection of heterogeneous elements.

 Array: memory allocated is static and continuous.

 List:  memory allocated is dynamic and Random.

Array:  User need not have to keep in track of next memory allocation.

List:  User has to keep in Track of next location where memory is allocated.

Question 92. Does C++ Support Multilevel And Multiple Inheritance?

Answer :

Yes.

Question 93. What Is A Template In C++?

Answer :

Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:

template <class indetifier> functiondeclaration; template <typename indetifier> functiondeclaration;

The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

Question 94. Define A Constructor - What It Is And How It Might Be Called (2 Methods).

Answer :

constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized.
Ways of calling constructor:

Implicitly: automatically by complier when an object is created.

Calling the constructors explicitly is possible, but it makes the code unverifiable.

Question 95. You Have Two Pairs: New() And Delete() And Another Pair : Alloc() And Free(). Explain Differences Between Eg. New() And Malloc()

Answer :

"new and delete" are preprocessors while "malloc() and free()" are functions, [we dont use brackets will calling new or delete].

no need of allocate the memory while using "new" but in "malloc()" we have to use "sizeof()".

"new" will initlize the new memory to 0 but "malloc()" gives random value in the new alloted memory location [better to use calloc()]

Question 96. What Is The Difference Between Class And Structure In C++?

Answer :

Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

Question 97. What Is Rtti In C++?

Answer :

Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many homegrown versions with a solid, consistent approach.

Question 98. What Is Encapsulation In C++?

Answer :

Packaging an object's variables within its methods is called encapsulation.

Question 99. What Is A C++ Object?

Answer :

Object is a software bundle of variables and related methods. Objects have state and behavior.

Question 100. Describe Private, Protected And Public - The Differences And Give Examples.

Answer :

class Point2D{ int x; int y;

public int color;

protected bool pinned;

public Point2D():x(0),y(0){} //default(no argument) constructor

};

Point2D MyPoint;

You cannot directly access private data members when they are declared (implicitly) private:

MyPoint.x = 5;          // Compiler will issue a compile ERROR

//Nor yoy can see them:

int xdim = MyPoint.x;  // Compiler will issue a compile ERROR

On the other hand, you can assign and read the public data members:

MyPoint.color = 255;      //no problem

int col = MyPoint.color; // no problem

With protected data members you can read them but not write them:

bool isPinned = MyPoint.pinned; // no problem.

Question 101. Stl Containers - What Are The Types Of Stl Containers?

Answer :

There are 3 types of STL containers:

Adaptive containers like queue, stack.

Associative containers like set, map.

Sequence containers like vector, deque.

Question 102. Rtti - What Is Rtti In C++?

Answer :

RTTI stands for "Run Time Type Identification". In an inheritance hierarchy, we can find out the exact type of the objet of which it is member. It can be done by using:

dynamic id operator.

typecast operator.

Question 103. Assignment Operator - What Is The Diffrence Between A "assignment Operator" And A "copy Constructor"?

Answer :

In assignment operator, you are assigning a value to an existing object. But in copy constructor, you are creating a new object and then assigning a value to that object.
For example:

complex cl,c2;

cl=c2;           //this is assignment

complex c3=c2;  //copy constructor.

Question 104. If You Hear The Cpu Fan Is Running And The Monitor Power Is Still On, But You Did Not See Anything Show Up In The Monitor Screen. What Would You Do To Find Out What Is Going Wrong?

Answer :

I would use the ping command to check whether the machine is still alive(connect to the network) or it is dead.

Question 105. Can You Be Able To Identify Between Straight- Through And Cross- Over Cable Wiring? And In What Case Do You Use Straight- Through And Cross-over?

Answer :

Straight-through is type of wiring that is one to connection, Cross- over is type of wiring which those wires are got switched We use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross¬over cable when connect between two NIC Adapters or sometime between two hubs.

Question 106. What Are The Defining Traits Of An Object-oriented Language?

Answer :

The defining traits of an object-oriented langauge are:

encapsulation,

inheritance,

polymorphism.

Question 107. What Methods Can Be Overridden In Java?

Answer :

In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.

Question 108. In C++, What Is The Difference Between Method Overloading And Method Overriding?

Answer :

Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

Question 109. What Is The Difference Between Mutex And Binary Semaphore?

Answer :

semaphore is used to synchronize processes, where as mutex is used to provide synchronization between threads running in the same process.

Question 110. Are There Any New Intrinsic (built-in) Data Types?

Answer :

Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords.

Question 111. What Problem Does The Namespace Feature Solve?

Answer :

Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.

This solution assumes that two library vendors don't use the same namespace identifier, of course.

Question 112. Describe Run-time Type Identification?

Answer :

The ability to determine at run time the type of an object by using the typeid operator or the dynamiccast operator.

Question 113. What Is The Standard Template Library (stl)?

Answer :

A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.

A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

Question 114. What Is An Explicit Constructor?

Answer :

A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It's purpose is reserved explicitly for construction.

Question 115. What Is A Mutable Member?

Answer :

One that can be modified by the class even when the object of the class or the member function doing the modification is const.

Question 116. When Is A Template A Better Solution Than A Base Class?

Answer :

When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class.

Question 117. Explain The Isa And Hasa Class Relationships. How Would You Implement Each In A Class Design?

Answer :

A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

Question 118. When Should You Use Multiple Inheritance?

Answer :

There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

Question 119. What Is The Difference Between A Copy Constructor And An Overloaded Assignment Operator?

Answer :

A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Question 120. What Is A Conversion Constructor C++?

Answer :

A constructor that accepts one argument of a different type.

Question 121. What Is A Default Constructor In C++?

Answer :

Default constructor WITH arguments

class B {

public:

B(int m=0):n(m){}
int n;

};

int main(int argc, char *argv[])

{ Bb;

return 0;

}

Question 122. How Does Throwing And Catching Exceptions Differ From Using Setjmp And Longjmp?

Answer :

The throw operation calls the destructors for automatic objects instantiated since entry to the try block.

Question 123. How Many Ways Are There To Initialize An Int With A Constant?

Answer :

There are two ways for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);

Question 124. What Are The Differences Between A C++ Struct And C++ Class?

Answer :

The default member and base-class access specifiers are different.

Question 125. Explain The Scope Resolution Operator?

Answer :

It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.

Question 126. How Do You Link A C++ Program To C Functions?

Answer :

By using the extern "C" linkage specification around the C function declarations.

Question 127. How Do I Initialize A Pointer To A Function?

Answer :

This is the way to initialize a pointer to a function

void fun(int a)

{

void main()

{

void (*fp)(int);

fp=fun;

fp(i);

}

}

Question 128. What Does Extern Mean In A Function Declaration In C++?

Answer :

It tells the compiler that a variable or a function exists, even if the compiler hasn't yet seen it in the file currently being compiled. This variable or function may be defined in another file or further down in the current file.

Question 129. How Do I Declare An Array Of N Pointers To Functions Returning Pointers To Functions Returning Pointers To Characters?

Answer :

If you want the code to be even slightly readable, you will use typedefs.

typedef char* (*functiontype_one)(void);

typedef functiontypeone (*functiontype_two)(void);

functiontype_two myarray[N]; //assuming N is a const integral

Question 130. What Is The Auto Keyword Good For In C++?

Answer :

Local variables occur within a scope; they are "local" to a function. They are often called automatic variables because they automatically come into being when the scope is entered and automatically go away when the scope closes. The keyword auto makes this explicit, but local variables default to auto auto auto auto so it is never necessary to declare something as an auto auto auto auto.

Question 131. What Is The Difference Between Char A[] = "string"; And Char *p = "string";?

Answer :

In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case if *p is assigned to some other value the allocate memory can change.

Question 132. What Can I Safely Assume About The Initial Values Of Variables Which Are Not Explicitly Initialized?

Answer :

It depends on complier which may assign any garbage value to a variable if it is not initialized.

Question 133. What Does Extern Mean In A Function Declaration?

Answer :

Using extern in a function declaration we can make a function such that it can used outside the file in which it is defined.

An extern variable, function definition, or declaration also makes the described variable or function usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined.

If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage.

Question 134. What Is The Best Way To Declare And Define Global Variables?

Answer :

The best way to declare global variables is to declare them after including all the files so that it can be used in all the functions.

Question 135. How Do You Decide Which Integer Type To Use?

Answer :

It depends on our requirement. When we are required an integer to be stored in 1 byte (means less than or equal to 255) we use short int, for 2 bytes we use int, for 8 bytes we use long int.

A char is for 1-byte integers, a short is for 2-byte integers, an int is generally a 2-byte or 4-byte integer (though not necessarily), a long is a 4-byte integer, and a long long is a 8-byte integer.

Question 136. Anything Wrong With This Code?

t*p = 0;

Delete P;

Answer :

Yes, the program will crash in an attempt to delete a null pointer.

Question 137. Anything Wrong With This Code?

t *p = Newt[10];

Delete P;

Answer :

Everything is correct, Only the first element of the array will be deleted", The entire array will be deleted, but only the first element destructor will be called.

Question 138. What Problems Might The Following Macro Bring To The Application?

Answer :

#define sq(x) x*x

Question 139. What Is An Html Tag?

Answer :

An HTML tag is a syntactical construct in the HTML language that abbreviates specific instructions to be executed when the HTML script is loaded into a Web browser. It is like a method in Java, a function in C++, a procedure in Pascal, or a subroutine in FORTRAN.

Question 140. Why Are Arrays Usually Processed With For Loop?

Answer :

The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a. length -1. That is exactly what a loop does.

Question 141. What Is Polymorphism In C++? Explain With An Example?

Answer :

"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object. Example: function overloading, function overriding, virtual functions. Another example can be a plus '+' sign, used for adding two integers or for using it to concatenate two strings.

Question 142. What Do You Mean By Pure Virtual Functions?

Answer :

A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. Pure virtual functions are equated to zero.

class Shape

{

public: virtual void draw() = 0;

};

Question 143. What Is A Scope Resolution Operator?

Answer :

A scope resolution operator (::), can be used to define the member functions of a class outside the class.

Question 144. What Is The Difference Between An External Iterator And An Internal Iterator? Describe An Advantage Of An External Iterator?

Answer :

An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.

Question 145. What Are Virtual Functions In C++?

Answer :

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

Question 146. What Is Abstraction In C++?

Answer :

Abstraction is of the process of hiding unwanted details from the user.

Question 147. Which Recursive Sorting Technique Always Makes Recursive Calls To Sort Subarrays That Are About Half Size Of The Original Array?

Answer :

Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in 0(n log n) time.

Question 148. What Is Friend Function In C++?

Answer :

As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

Question 149. What Is A C++ Class?

Answer :

Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.

Question 150. Suppose That Data Is An Array Of 1000 Integers. Write A Single Function Call That Will Sort The 100 Elements Data [222] Through Data [321]?

Answer :

quicksort((data + 222),100);

Question 151. What Is The Difference Between An Object And A Class?

Answer :

Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.

A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.

The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.

 An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

Question 152. What Are 2 Ways Of Exporting A Function From A Dll?

Answer :

1 .Taking a reference to the function from the DLL instance.
2. Using the DLL 's Type Library.

Question 153. What Do You Mean By Binding Of Data And Functions?

Answer :

Encapsulation.

Question 154. What Is The Word You Will Use When Defining A Function In Base Class To Allow This Function To Be A Polimorphic Function?

Answer :

virtual.

Question 155. What Is Virtual Class And Friend Class?

Answer :

Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.

Question 156. What Is Boyce Codd Normal Form In C++?

Answer :

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a-> , where a and b is a subset of R, at least one of the following holds:

a- > b is a trivial functional dependency (b is a subset of a).

a is a superkey for schema R.

Question 157. What Is A Copy Constructor And When Is It Called?

Answer :

A copy constructor is a method that accepts an object of the same class and copies it's data members to the object on the left part of assignement:

class Point2D{ int x; int y;

public int color;

protected bool pinned;

public Point2D() : x(0),y(0){} //default (no argument)constructor

public Point2D( const Point2D & );

};

Point2D::Point2D( const Point2D & p )

{

this->x = p.x; this->y = p.y;

this->color = p.color;

this->pinned = p.pinned;

}

main()

{

Point2D MyPoint;

MyPoint.color  = 345;

Point2D AnotherPoint = Point2D( MyPoint);

// now AnotherPoint has color = 345

Question 158. What Do You Mean By Inheritance?

Answer :

Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

Question 159. Can We Define A Constructor As Virtual In C++?

Answer :

No, we cannot define constructors as virtual because constructors have the same name as their classes and no two constructors of base-derived classes can have the same name. So, when we initialize an object of the base or derived class with the help of virtual constructors, the base constructor is invoked instead of the derived constructor. Therefore, it is not possible to define a constructor as virtual.

Question 160. Can We Declare A Base-class Destructor As Virtual?

Answer :

Yes, we can declare a base-class destructor as virtual that makes all derived-class destructors as virtual even if they do not have the same name as base-destructor. The problem arises when the derived class's pointer refers to a base class. For this reason, the base class destructor should be declared as virtual so that the appropriate destructor is called on calling the delete method of the base class object.

Question 161. How Does A Copy Constructor Differs From An Overloaded Assignment Operator?

Answer :

A copy constructor uses the value of an argument to construct a new object. We can use an overload assignment operator to assign the value of an existing object of the same class to another existing object in that class.

Question 162. Define The Process Of Error-handling In Case Of Constructor Failure?

Answer :

If the constructor does not have the return statement, then it indicates failure in handling the error by throwing an exception.

Question 163. What Is A Default Constructor?

Answer :

A zero-argument constructor or a constructor in which all the arguments have default values is called a default constructor.

For example:

A Al; // default constructor called.

Question 164. Define The Process Of Handling In Case Of Destructor Failure?

Answer :

In order to handle a failed destructor, you need to write a message to a log file; however, do not throw an exception. There is a rule in C++ that exception cannot be thrown from a destructor, which is called when the process of "stack unwinding" occurs in other exceptions. For example, if someone says throw waste files(), the stack frames between the throw waste files() and the catch (waste files) will get popped. This is known as stack unwinding. It is the process of destroying all the local objects related to those stack frames and calling destructors in case of throwing of an exception by one of those destructors. For example, if an object named Bar is thrown, then the C++ runtime system is in a neutral situation means either to avoid the Bar and end up in the catch (waste files) or ignore the function Foo and look for a catch (Bar) handler. It will call in the terminate () process to end the program.

Question 165. What Is A Virtual Destructor?

Answer :

Virtual destructors help in destroying objects without knowing their type. With the help of the virtual function mechanism, the appropriate destructor for the object is invoked. In the case of abstract classes, destructors can also be declared as pure virtual functions. For example, class A derives from class B. Then, on calling the derived class dynamically at the execution time, the destructor will first call the derived class that is class A, and then the base class that is class B.

It is important to note that theVirtual keyword, when used with the destructor, ensures the calling of all the derived and base class destructors and therefore helps in the proper execution and closing of the program.

Question 166. Can You Explicitly Call A Destructor On A Local Variable?

Answer :

No, the destructor is called when the block closes in which the local variable was created.
If a destructor is called explicitly twice on the same object, the result ends in an undefined behavior because the local variable gets destroyed when the scope ends.

Question 167. What Are Shallow And Deep Copies?

Answer :

A shallow copy is used to copy actual values of the data. It means, if the pointer points to dynamically allocated memory, the new object's pointer in the copy still points to items inside the old objects and the returned object will be left pointing to items that are no longer in scope. A copy of the dynamically allocated objects is created with the help of a deep copy. This is done with the help of an assignment operator, which needs to be overloaded by the copy constructor.

Question 168. What Do You Understand By Zombie Objects In C++?

Answer :

In a situation, where an object is created in a class, a constructor fails before its full execution. It is very difficult to ensure about the execution of the constructor whether the constructor would return a value or not. Objects that are no more required for an application are called zombie objects. These zombie objects occupy a space in the memory and wait for their termination.

Question 169. Should The This Pointer Can Be Used In The Constructor?

Answer :

We can use the this pointer in the constructor in the initialization list and also in the body. However, there is a feeling that the object is not fully formed so we should not use this pointer. Let's understand the use of the this pointer with the help of the following example. The declared data members of a base class and/or the declared data members of the constructor's own class can be accessed by the constructor {body} and/or a function called from the constructor. This is possible because of the full construction of constructor's body at the time of execution. The preceding example always works.

The override in the derived class is not possible for a function called from the constructor and the {body} of a constructor which is independent of calling the virtual member function by the explicit use of the this pointer.

Please make sure that the initialization of other data member has already been done before passing the data member to another data member's initializer in this object. With the help of some straightforward language rules (independent of the specific compiler that you are using), you can confirm about the determination of initialization of data members.

Without the prior knowledge of these rules, there is no use of passing any data member from the this object.

Question 170. What Do You Understand By A Pure Virtual Member Function?

Answer :

A virtual function with no body structure is called a pure virtual member function. You can declare a pure virtual member function by adding the notation =0 to the virtual member function declaration. For example, area () is a virtual function, but when it is declared as shown in the following expression, it becomes a pure virtual member function: virtual int area () =0;

To avoid a compilation error, all the classes need to implement pure virtual classes that are derived from the abstract class.

Question 171. How Can Virtual Functions In C++ Be Implemented?

Answer :

When a class has at least one virtual function, the compiler builds a table of virtual function pointers for that class. This table, commonly called the v-table, contains an entry for each virtual function in the class. The constructor of the class is used to create this table. Each object of the class in memory includes a variable called the vptr, which points to the class's common vtbl. The _rst (which creates the vtable) is constructed by the base classes after the construction of the derived classes. The derived class constructor overwrites the entries of the vtable, if its constructor overrides any virtual function of the base class. Therefore, you need not call every function from a constructor just to avoid the error prone scenario of calling the Base class constructor instead of the derived class constructor (which fails to set the entries of objects of vtable).

Question 172. What Do You Understand By Pure Virtual Function? Write About Its Use?

Answer :

A pure virtual function in a base class must have a matching function in a derived class. A program may not declare an instance of a class that has a pure virtual function. A program may not declare an instance of a derived class if that derived class has not provided an overriding function for each pure virtual function in the base. If you want programmers to override certain functions in a class, such as those that need information customized for a particular installation, you should make these functions pure virtual.

Question 173. How The Virtual Functions Maintain The Call Up?

Answer :

The call is maintained through vtable. Each object includes a variable known as vptr, which points to the class's common vtable. It contains an entry for every virtual function. On calling the function, vtable calls the appropriate function using vptr.

Question 174. Write A Note About Inheritance?

Answer :

Inheritance is a mechanism that allows the object of one class to utilize the form and model or behavior of another class. A class derived from the base class inherits attributes, functions, or methods that implement the base class to the derived class and also extends the derived class by overriding functions and adding new additional attributes and functionalities.

Question 175. What Is The Need Of Multiple Inheritance?

Answer :

The multiple inheritance allows you to define a new class that inherits the characteristics of several base classes which are not related to each other. The vehicle class encapsulates the data and behavior that describe vehicles along with other information, such as date of purchase, life, and maintenance schedules. Classes that support specific kinds of vehicles, such as trucks, airplanes, and cars are also derived from the vehicle class. The asset class encapsulates the data and behavior of the organization's assets, including acquiring date, and depreciation schedule data for accounting purposes. A company car, being both a vehicle and an asset, is represented by a class that derives from both base classes.

Question 176. How Can You Say That A Template Is Better Than A Base Class?

Answer :

In case of designing a generic data type to manage objects of other data types which are unknown to their container class, a template is preferred over a base class. A template can contain more than one data type parameter, making it possible to build parameterized data types of considerable complexity. The class template also allows the declaration of more than one object in the same program.

Question 177. Explain The Concept Of Multiple Inheritance (virtual Inheritance). Write About Its Advantages And Disadvantages?

Answer :

Multiple inheritance is defined as the ability of a derived class to inherit the characteristics of more than one base class. For example, you might have a class zoo which inherits various animal classes. The advantage of multiple inheritance is that you can create a single derived class from several base classes. It helps in understanding the logic behind these complex relationships.

The multiple inheritance is not preferred by the programmers because with multiple base classes, there are chances of conflicts while calling a method in the sub class that exists in both the base classes. For example, if you have a class named zoo that inherits both the Anaconda and Zebra classes, then each base class might define a different version of the method walk, which creates a conflicting situation.

Question 178. Describe Inheritance And Non-inheritance Of A Derived Class?

Answer :

Using inheritance, you can derive all the data members and all the other common functions of the base class and still retain the functionality of the common methods of the base class. For example, the animal class with eat, sleep and breathe methods comprises the base class because they are common to all animals. Now, a new class Elephant with a method trumpet is derived from the class animal. With the help of inheritance, the Elephant class inherits the trumpet method and still retains the eat, sleep, and breathe methods from the base class, animal.

Therefore, you can add new methods to an existing class with the retaining of common methods. There are few methods that are not inherited on creating a derived class which includes constructors, destructors, and assignment operator methods of their base classes.

Question 179. Write A Note About The Virtual Member Function?

Answer :

A virtual function is a member function of the base class and relies on a specific object to determine which implementation of the function is called. However, a virtual function can be declared a friend of another class. If a function is declared virtual in a base class, you can still access it directly using the :: operator. Note that if you do not override a virtual member function in a derived class, a call to that function uses the function implementation defined in the base class.

Question 180. Should The Member Functions Which Are Made Public In The Base Class Be Hidden?

Answer :

As the public member functions of the base class are necessary to implement the public interface of the class, the member functions which are made public in the base class should never be hidden. When you are designing a class, make the derived data members private because a private member of the derived class is accessed through the protected or public member functions of the base class.

Question 181. Can Circle Be Called An Ellipse?

Answer :

Yes, a circle can be called an ellipse. Let's understand this concept with the help of an example, if ellipse has a member function named as setsize with the widthQ of the object as x and its height() as y. There are two kinds of relationships that exist between a circle and an ellipse:

Circle and ellipse can be made as two different classes :

In this case, ellipse can be derived from AsymmetricShape class and has a member function named as setSize(x,y). On the contrary, circle can be derived from SymmetricalShape class and has a member function named as setSize(size). Therefore, they both are unrelated in its member functions as well as in their derivations.

 Circle and ellipse can be derived from a base class :

In this case, circle and ellipse both can be inherited from the class Oval because class Oval can only have setSize(size) member function which sets the height() and widthQto the size of the object.

Question 182. Why Do We Separate Interface From Implementation?

Answer :

The interface is visible to the user of the class and consists of public members, which are usually member functions. The class user reads and modifies values in data representation by calling public member functions. The interface is generic in that it is not bound to any particular implementation.

The implementation of a class, which consists of private data members and private member functions, is essentially hidden from the program. The implementation defines the details of how the class implements the behavior of the abstract base type. The class author should be able to change the implementation without affecting the program.

Question 183. How Can You Differentiate Between Inheritance And Implementation In C++?

Answer :

With the help of abstract base classes, we can differentiate between interface and implementation in C++.

Question 184. Write About Abstract Base Classes?

Answer :

An abstract base class is a class definition that is always a base class for other classes to be derived from. No specific objects of the base class are declared by the program. A C++ abstract base class is one that has a pure virtual function, a protected constructor, or a protected destructor.
At the design level, you create a pure virtual method by using = 0 in place of a method body. This notation specifies that the member function is a pure virtual function. This means that the base class is an abstract base class, and the class designer intends the class to be used only as a base class. The base class may or may not provide a function body for the pure virtual function. In either case, a program that uses this class may not directly declare any objects of the abstract base class. If the program declares an object of a class directly or indirectly derived from the abstract base class, the pure virtual function must be overridden explicitly.

Question 185. Which Should Be More Useful: The Protected And Public Virtuals?

Answer :

Public virtuals are more preferable than protected virtuals. Public virtuals permit a program to directly modify the values of data members. It can be accessible to any function that is within the scope of the structure. It translates the implementation for the user of the class. It is the most common, convenient, and easiest way to implement by any of the programs.
On the other hand, protected virtual functions are used for hiding some methods or data members from the outside class making it consistent and symmetrical in its approach. It is condition specific, so not commonly used.

Question 186. Describe The Setting Up Of My Member Functions To Avoid Overriding By The Derived Class?

Answer :

To avoid overriding of the member functions by the derived class, the leaf method is used. With the help of the leaf method, it is possible to leave the code unaligned at the time of execution by simply adding a comment next to the method. This method is easy, fast, and inexpensive to use.

Question 187. How Do C++ Struct Differs From The C++ Class?

Answer :

C++ defines structures and classes almost identically. To declare a class, you use the class keyword in place of the struct keyword. The only other differences are related to the default access specifiers. The members of a structure have public access by default; whereas, the member of a class has private access by default. The concept of encapsulation is supported by the class only and not the structure.

Question 188. Write About The Use Of The Virtual Destructor?

Answer :

When an object is declared with the new operator and the pointer type is that of a base class with a non-virtual destructor, the base destructor executes instead of the derived destructor. When a base class destructor is virtual, the compiler calls the correct destructor function irrespective of the type of the pointer.
If the base class needs no custom destruction, you must still provide a virtual destructor (with an empty block) to permit the proper destructor calls for dynamically allocated objects. Moreover, by making the destructor of the base class as virtual, you can invoke the destructors of both the base and derived classes in the reverse order.

Question 189. Write A Note On Encapsulation?

Answer :

Encapsulation is an object-oriented design approach that closely binds the implementation of a class to its data representation, logically hides the details of the implementation from users of the data type, and provides a public interface to the data type's behavior. It implies an implementation, which is hidden from the class user, and an interface, which is visible to the class user. It helps you to handle large scale programming tasks.The idea behind encapsulation is to take a complex system that demands a lot of attention and to turn it into an object that handles all its work internally and can easily form a concept.

Question 190. What Are The Effects After Calling The Delete This Operator ?

Answer :

It is difficult for the compiler to know whether an object is allocated on a stack or a heap. On invoking the delete this operator, the destructor is called twice on the object related to the current context. Firstly implicitly and secondly explicitly. It results in undefined behavior and error-prone conditions. The delete this operator can only work on three conditions:

 An Instantiation of a local variable should not take place, after calling the delete this destructor.

 The this pointer should not be used after calling the delete this operator.

 The object of a derived class should be allocated and initialized with the new operator

Question 191. Write About All The Implicit Member Functions Of A Class?

Answer :

All the implicit member functions of a class are listed as follows:
a. Default constructor —Defines a constructor with no parameters.
b. Copy constructors —Initializes the value from an existing object of a class to a new, instantiated object of that same class.
c. Assignment operator—-Returns a value.
d. Default destructor—Runs automatically when an object is being destroyed.
e. Address operator —Takes one operand and returns the memory address of a variable or function.

Question 192. What Is Overriding?

Answer :

To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list.
Overriding a method means replacing the method's functionality in a child class. To implement overriding functionality, you need parent and child classes. In the child class, you define the same method signature as the one defined in the parent class.

Question 193. Write About The Members That A Derived Class Can Add?

Answer :

Derived classes can use the constructors, destructors, and assignment operator methods of their base classes. It can also override the member functions of the base class. For example, if the base class has an assignment operator method, the compiler uses that method for the derived class as well, which is fine unless the derived class also adds its own data members (in which case, you should create a new operator = method for the derived class).

Question 194. Describe The Process Of Creation And Destruction Of A Derived Class Object?

Answer :

When you declare an object of a derived class, stacks or heaps allocate the space for the object. This space contains the inherited data members from the base class and also the members defined in its derived class. The initialization of the inherited data members from the base class is done with the help of the constructor of a base class. Therefore, compiler executes the constructor function of the base class followed by the constructor function of the derived class.
When an object goes out of scope, the destructors execute in the reverse order of the constructors. Firstly, the destructor of the derived class is invoked to destroy the derived class object, and then the destructor of a base class is invoked. This process helps to allocate the required space.

Question 195. What Is An Object?

Answer :

An object is a declared instance of a data type, which includes standard C++ data types as well as objects of classes. In other words, they are the variables that you declare in the class. In OOP, objects represent real world entities, such as students, doctors, and bank accounts. These objects can interact with each other by sending or receiving messages. An object has the following three main characteristics:

 It has a state

 It may or may not display a behavior

 It has a unique identity

Question 196. Define A Good Interface?

Answer :

A good interface is the one that hides unnecessary details and provides a simplified way for making applications with all the required information and different software related to different applications. A good interface should provide users an opportunity to explore and understand the different concepts related to the tasks they want to do. In this way, it ensures good communication between the user and the computer.

Question 197. Write About The Role Of C++ In The Tradeoff Of Safety Vs. Usability?

Answer :

Earlier in C, an encapsulation is achieved by making the methods static in a class. On the contrary, in C++, it would not work.

Programmers use structs in C for making multiple instances. The creation of multiple instances is not supported directly by the data with static keyword in a class. This situation made the concept of tradeoff between safety (information hiding) and usability (multiple instances) worse.
On the contrary, C++ supported both multiple instances and encapsulation with the help of the concept of a class. The public part of a class includes the interface of the class which includes public member functions and friends functions of a class. The private and/or protected parts of a class includes an implementation of the class which includes the data. This results in a struct which is encapsulated. This depicts the strong tradeoff between safety (information hiding) and usability(multiple instances).

Question 198. How Can You Prevent Accessing Of The Private Parts Of My Class By Other Programmers (violating Encapsulation)?

Answer :

Encapsulation only hides the details of the implementation from users of the data type, and provides a public user interface. Encapsulation only maintains the integrity of the internal coding inside the methods of a class, but not able to prevent accessing the private or protected parts of a class by the user.

Question 199. Can Non-public Members Of Another Instance Of The Class Be Retrieved By The Method Of The Same Class?

Answer :

Yes, the non-public members of another instance of the class can be retrieved by the method of the same class. Retrieval depends on the type of the class whether it is of a reference/pointer/object class. It seems to break the rule of encapsulation. However, there is a need of get () method with a public specifier for the non-public members to retrieve the method of the same class because an explicit argument (means the pointer by which "this" is not called) can be taken by at least one method of the same class.

Question 200. Can Encapsulation Be Called As A Security Device?

Answer :

Encapsulation hides important and classified data from accidental manipulation by members of the same program. Note that the encapsulated data of a class can be accessible outside the class only when the data is used in the function of the class. However, a limited number of operations can be performed on encapsulated data by executing the functions or methods of the class. An encapsulation prevents the internal error to occur and not the explicit attacks or intentional attacks and therefore cannot be called as a security device.

Question 201. How The Keyword Struct Is Different From The Keyword Class In C++?

Answer :

In C++, a class is similar to a struct with the exception that, by default, all the members of a class are private; while the members of a struct are public. Encapsulation is not supported by structures but supported by classes.

Question 202. How New/delete Differs From Malloc()/free?

Answer :

The memory uses the malloc() operator, which in turn uses the free operator, to remove the unnecessary programs. On the other hand, the program builds the array by using the new operator, fills it with random numbers, displays each of the elements in the array, and deletes the array by using the delete operator. The new and delete operators should be used in C++ because they are type safe. The malloc operator is used when there is a need of forcing a type on an object because a void pointer is returned by it. Moreover, that object cannot be assigned to other types.

Question 203. How The Delete Operator Differs From The Delete[]operator?

Answer :

When the new[] operator is used to allocate memory dynamically, the delete[]operator is used to free the memory. The new[] operator is used to allocate memory to an array of values, which starts with the index 0.

Question 204. How A New Operator Differs From The Operator New?

Answer :

The new operator creates a class's new instance. On the other hand, overloading of a new operator is done globally with the help of the operator new. The new operator allocates memory for the item and assigns the address of that memory to the pointer by using the name of an item with a pointer of a data type, structure, or array. For example, consider the following code snippet:

Double * pi = new double;

In the preceding code snippet, the new operator returns a pointer to the double variable, because it allocates the space for a double value.

Question 205. Explain The Term Memory Alignment?

Answer :

The primary meaning of the term alignment is to maintain the appropriate positioning of different components in the memory with respect to each other. In C++, there is a requirement of setting of various objects and variables in a particular way in the system's memory.Therefore, many data variables are aligned automatically by the compiler according to their processor and type.

Question 206. Can A New Be Used In Place Of Old Mallocq? If Yes, Why?

Answer :

The new operator should be used in place of old malloc because the new operator ensures the calling of an appropriate destructor at the time of execution and also it is more type-safe than mallocQ.

Question 207. Is It Possible To Use A New For The Reallocation Of Pointers ?

Answer :

The reallocation of pointers cannot be done by using new. It can be done by using the reallocQ operator.

Question 208. On Throwing An Exception By The Animal Constructor In P = New Animalq, Can Memory Leak Occur?

Answer :

Memory of an animal class cannot leak by throwing an exception in p = new Animal(). In case of occurrence of an exception during the Animal constructor of p = new Animal(),there is a surety of the automatic releasing of the allocated memory back to the heap.

Question 209. What Would Happen On Forgetting [], While Deallocating An Array Through New?

Answer :

If you forget to use [] while deallocating an array through new, it throws a run time or compile time exception and results in the corruption of the heap.Therefore, it is the responsibility of the programmer to establish the connection between T[n] and delete[]p correctly.

Question 210. Write About The Retrieval Of N Number Of Objects During The Process Of Delete[]p?

Answer :

The n number of objects can be retrieved with the help of the pointer p (it stores the n number of objects) at the run time.

This can be achieved by the application of two techniques, which are:

An array which can be associated with p in the form of key and a value such as n.

Over-allocation of the array can be done. The preceding techniques are used by the compilers of commercial grade.

Question 211. Is It Possible For A Member Function To Use Delete This?

Answer :

It is possible for a member function to use delete this but on certain conditions which are as follows:

 Ensure that the allocation of this object is done through new[] operator.

Ensure that the invocation of a member function done on this (current) object will be the last member function.

Ensure that calling of other member functions and data members should not be done after the line of code which includes delete this.

Examination or comparison of this pointer with other pointers and NULL, printing or casting it, must be avoided after using the delete this.

The preceding points are applied in the cases where the this pointer belongs to the base class in the absence of the virtual destructor.

Question 212. Discuss The Effects Occur, After An Exception Thrown By A Member Function Is Unspecified By An Exception Specification?

Answer :

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).

Question 213. How Can I Be Thrown Polymorphically?

Answer :

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.

Question 214. What Is The Role Of Copy Constructor In Copying Of Thrown Objects?

Answer :

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.

Question 215. How Can An Improvement In The Quality Of Software Be Done By Try/catch/throw?

Answer :

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.

Question 216. What Is A Dangling Pointer?

Answer :

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.

Question 217. Explain The Concept Of Memory Leak.

Answer :

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.

Question 218. List The Issue That The Auto_ptr Object Handles?

Answer :

The auto_ptr object is used to deallocate memory, which is allocated to a variable, when the variable goes out of scope.

Question 219. What Are Smart Pointers?

Answer :

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.

Question 220. How A Pointer Differs From A Reference?

Answer :

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.

Question 221. How Const Int *ourpointer Differs From Int Const *ourpointer?

Answer :

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.

Question 222. Explain How Overloading Takes Place In C++?

Answer :

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.

Question 223. What Is The Difference Between Prefix And Postfix Versions Of Operator++()?

Answer :

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 ++().

Question 224. Describe The Advantages Of Operator Overloading?

Answer :

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.

Question 225. Provide Some Examples Of Operator Overloading?

Answer :

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

Question 226. Can The Operator == Be Overloaded For Comparing Two Arrays Consisting Of Characters By Using String Comparison?

Answer :

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.

Question 227. Can The Creation Of Operator** Is Allowed To Perform The To-the-power-of Operations?

Answer :

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.

Question 228. What Is The Main Purpose Of Overloading Operators?

Answer :

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 [].

Question 229. Specify Some Guidelines That Should Be Followed While Overloading Operators?

Answer :

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.

Question 230. Explain The Concept Of Friend Function In C++?

Answer :

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.

Question 231. How The Programmer Of A Class Should Decide Whether To Declare Member Function Or A Friend Function?

Answer :

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.

Question 232. Why Should We Use Null Or Zero In A Program?

Answer :

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.

Question 233. Is Recursion Allowed In Inline Functions?

Answer :

Syntactically, the recursion (calling of the function by itself) is allowed in inline function but practically, the inline functions and their properties do not remain inside the program. Moreover, the compiler is not sure about the depth of the recursion at the time of compilation.

Question 234. Write About The Scope Resolution Operator?

Answer :

The scope resolution operator (::) can be used to define the member functions of a program outside the boundary of a class and not within the class specifier. The global scope resolution operator, which is coded as a prefix to the variable's name (for example,:: varname), lets you explicitly reference a global variable from a scope in which a local variable has the same name.

A program can use scope resolution operator (::) to bypass the override of a base class member that a derived class has overridden.

Question 235. Is It Possible For A Member Function To Delete The Pointer, Named This?

Answer :

It is possible for a member function to use delete this pointer but on certain conditions.
The conditions which allow the member function to use delete this are listed in the following order:

Make sure that the allocation of this (current) object is done through new [] operator only.

Make sure that the invocation of your member function done on this (current) object will be the last member function. It made the calling of the last member function by the current object easy.

Make sure that calling of other member functions and data members should not be done after the line of code which includes delete this.

Examination or comparison of this pointer with other pointers and with NULL, printing or casting it, must be avoided after using the delete this line.

Question 236. Name The Debugging Methods That Are Used To Solve Problems?

Answer :

The following are the debugging methods used by C++ to solve problems:

 GOB—Allows debugging of the global objects which have the reference

 Forte —Used as a debugger for building the application based on high performance

 Visual ^:udio —Traces the program's source code and supports break-points, watchpoints, and threads

 Tusc —Traces the last call of the system before its termination

Question 237. Write About The Various Sections Of The Executable Image?

Answer :

The sections of an executable image are as follows:
a. The different sections of data, such as the section of the data which is not initialized and the initialized section of the variable of the data
b. The specific section of the code
c. The allocation of all the static variables is done in the variable section which is initialized.

Question 238. Discuss The Possibilities Related To The Termination Of A Program Before Entering The Mainq Method?

Answer :

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.

Question 239. What Is Meant By The Term Name Mangling In C++?

Answer :

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.

Question 240. How A Macro Differs From A Template?

Answer :

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.

Question 241. Write About C++ Storage Classes?

Answer :

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.

Question 242. What Are The Advantages Of Using Const Reference Arguments In A Function?

Answer :

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.

Question 243. What Kind Of Problems Can Be Solved By A Namespace?

Answer :

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

}

Question 244. Why Do We Use The Using Declaration?

Answer :

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.

Question 245. Write About An Iterator Class?

Answer :

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.

Question 246. Write About The Stack Unwinding?

Answer :

Stack unwinding is a process in which a destructor is invoked in a particular program for destroying all the local objects in the stack between throwing and catching of an exception.

Question 247. In Which Situation The Program Terminates Before Reaching The Breakpoint Set By The User At The Beginning Of The Mainq Method?

Answer :

In C++, the initialization of variables is allowed before the calling of the main() method. If a function is invoked by the global variable's initialization and termination is done, then it results in the error before entering of the main() method.

Question 248. If I Is An Integer Variable, Which Is Faster ++i Or I++?

Answer :

In ++i which is a pre-increment method, there is only one instruction which is needed for incrementing the variable for returning a new value. In the case of i++ which is a post-incremental method, there is a need for two instructions -one for saving the old compiler which is used in the expression and the other for the incrementation of the variable. In the post-incremental method, first the old value is returned and then the variable is incremented. This process is slower than the pre-incremental process.

Question 249. How Can I Disable The "echo" Feature?

Answer :

The disabling of the echo feature is done with the help of the getpassQ function. The character keys are turned off by using the getpass(3) function.

Question 250. How Can You Link A C Program With A C Function?

Answer :

A C program can be linked with a C function with the help of the extern "C" linkage specification. The name mangling in C++ encodes all the codes into the symbol and therefore results in errors. Therefore, the references of these symbols should be avoided by the C compiler. One should have the knowledge about the mangled function and type-safe linkages. During the compilation, with the extern "C" linkage specification, the name mangling feature is turned off to ensure the proper linkage of the C program to the C functions.

Question 251. How Are The Features Of C++ Different From C?

Answer :

All the features of C are similar to C++ except some features, such as polymorphism, inheritance, operator overloading which are supported in C++ but not in C language. Both C and C++ language is similar in their functionality but C++ provides with more tools and options.

Question 252. How Can A Struct In C++ Differs From A Struct In C?

Answer :

The differences between struct in C++ and C are listed in the following points:

 In C and C++, the variables of the structures are public; however, in C, the variable cannot be declared as private or protected. On the contrary, in C++, the variables can be declared as private or protected.

On declaring a struct in C, the addition of the struct keyword is must. On the contrary, there is no need of the struct keyword on declaring struct in C++.

 In C, structures do not have direct functions or methods (procedures). Example, pointers inside the functions. On the other hand, C++ has direct functions or methods, for example classes.

 In C, the initialization cannot be done outside the scope of a structure. However, in C++, the initialization can be done outside the scope of a structure.

 In C, the concept of inheritance is not supported. In C++, the concept of inheritance is fully supported.

Question 253. What Happens When The Extern "c" Char Func (char*,waste) Executes?

Answer :

On executing the extern "C" char func (char*,waste), the link to the code compiled by the C compiler can be established by the programmer because the "name mangling" (which includes the tokens that identify the function's return type and the types of its arguments) will be turn off for the function.

Question 254. Write About The Access Privileges In C++ And Also Mention About Its Default Access Level?

Answer :

There are three access privileges provided in C++ which are private, protected, and public. The members of a class have private access by default.The public members can be accessed by member functions and by other functions that declare an instance of the class. The private members can be accessed by member functions of the same class. The protected members are included by using the class inheritance. The protected members can be accessed only within the class.

Question 255. Describe The Role Of The C++ In The Tradeoff Of Safety Vs. Usability?

Answer :

Earlier in C, encapsulation is meant to hide the information. Encapsulation is included in C by making other class members static in a class to prevent accessing the members by another module. However, the concept of multiple instances is not supported by the encapsulation because it is impossible to directly make multiple instances inside the static class module. If there is a need of multiple instances, a struct is used. On the contrary, encapsulation is not supported by structs.
In C++, a class supports both encapsulation and multiple instances. The class's interface that contains the public member functions and friend functions of the class can be accessed by multiple users. On the other hand, an implementation of the class is defined by the private and protected parts of a class. This encapsulated part forms a struct; thereby, reducing the tradeoff (loosing of one quality as a result of gaining of another quality) between the encapsulation and usability.

Question 256. Define What Is Constructor ?

Answer :

A constructor is a method that is called when a new instance of an object of a class is created. It initializes all class members whenever you create an object of the class. It is a member function with the same name as its class. It may or may not take any parameters. It does not have any return type.