Thursday, 12 April 2018

C++ Interview Questions & Answers

  1. Question1. 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 ; }
  2. Question2. 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 ; } };
  3. Question3. 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;
  4. Question4. 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 ; }

  5. Question5. 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. 
    Question6. Refer To A Name Of Class Or Function That Is Defined Within A Namespace?

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

  2. Question7. 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 }

  3. Question8. 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.

  4. Question9. 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.

  5. Question10. 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. 
    Question11. 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.

  1. 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( ) ; }

  2. Question12. 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.

  3. Question13. 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.

  4. Question14. 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.

  5. Question15. 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.

  6. Question16. 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.

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

  8. Question18. 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.

  9. Question19. 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.

  10. Question20. 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.
  11. Question21. 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.
  12. Question22. 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.
  13. Question23. 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(
  14. Question24. 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.
  15. Question25. 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.
  16. Question26. 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 ; }
  17. Question27. 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.
  18. Question28. 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.
  19. Question29. 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.
  20. Question30. 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.
  21. Question31. 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.
  22. Question32. 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.
  23. Question33. 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.
  24. Question34. 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 ; }
  25. Question35. 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( ).
  26. Question36. 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.
  27. Question37. 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.
  28. Question38. 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.
  29. Question39. 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.
  30. Question40. 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.
  31. Question41. 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.
  32. Question42. 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.
  33. Question43. 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 ;
  34. Question44. 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 ) ; }
  35. Question45. 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.
  36. Question46. 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.
  37. Question47. 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.
  38. Question48. 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++.
  39. Question49. 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; } };
  40. Question50. 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.
  41. Question51. 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.
  42. Question52. 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.
  43. Question53. 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.
  44. Question54. 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.
  45. Question55. 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.
  46. Question56. 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.
  47. Question57. 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.
  48. Question58. Differentiate Between The Message And Method In C++?
    Answer :
    Message in C++ :
    1. Objects communicate by sending messages to each other.
    2. A message is sent to invoke a method in C++.
    Method in C++ :
    1. Provides response to a message.
    2. It is an implementation of an operation in C++.
  49. Question59. 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.
  50. Question60. 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.
  51. Question61. 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.
  52. Question62. 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.
  53. Question63. 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.
  54. Question64. 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.
  55. Question65. 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.
  56. Question66. Name Some Pure Object Oriented Languages?
    Answer :
    pure object oriented languages are Smalltalk, Java, Eiffel, Sather.
  57. Question67. What Is A Node Class In C++?
    Answer :
    A node class is a class that,
    1. relies on the base class for services and implementation.
    2. provides a wider interface to the users than its base class.
    3. relies primarily on virtual functions in its public interface.
    4. depends on all its direct and indirect base class.
    5. can be understood only in the context of the base class.
    6. can be used as base for further derivation.
    7. 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.
  58. Question68. 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.
  59. Question69. 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.
  60. Question70. 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; } }
  61. Question71. 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.
  62. Question72. 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.
  63. Question73. 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).
  64. Question74. 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.
  65. Question75. 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.
  66. Question76. Write A Struct Time Where Integer M, H, S Are Its Members
    Answer :
    struct Time { int m; int h; int s; };
  67. Question77. How Do You Traverse A Btree In Backward In-order?
    Answer :
    1. Process the node in the right subtree.
    2. Process the root.
    3. Process the node in the left subtree.
  68. Question78. What Is The Two Main Roles Of Operating System?
    Answer :
    • As a resource manager.
    • As a virtual machine.
  69. Question79. In The Derived Class, Which Data Member Of The Base Class Are Visible?
    Answer :
    In the public and protected sections.
  70. Question80. 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.
  71. Question81. 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).
  72. Question82. 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; }
  73. Question83. 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.
  74. Question84. 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; } }
  75. Question85. 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.
  76. Question86. 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; }
  77. Question87. 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«",";
  78. Question88. 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.
  79. Question89. 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; }
  80. Question90. 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.
  81. Question91. 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.
  82. Question92. Does C++ Support Multilevel And Multiple Inheritance?
    Answer :
    Yes.
  83. Question93. 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.
  84. Question94. 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:
    1. Implicitly: automatically by complier when an object is created.
    2. Calling the constructors explicitly is possible, but it makes the code unverifiable.
  85. Question95. You Have Two Pairs: New() And Delete() And Another Pair : Alloc() And Free(). Explain Differences Between Eg. New() And Malloc()
    Answer :
    1. "new and delete" are preprocessors while "malloc() and free()" are functions, [we dont use brackets will calling new or delete].
    2. no need of allocate the memory while using "new" but in "malloc()" we have to use "sizeof()".
    3. "new" will initlize the new memory to 0 but "malloc()" gives random value in the new alloted memory location [better to use calloc()]
  86. Question96. 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.
  87. Question97. 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.
  88. Question98. What Is Encapsulation In C++?
    Answer :
    Packaging an object's variables within its methods is called encapsulation.
  89. Question99. What Is A C++ Object?
    Answer :
    Object is a software bundle of variables and related methods. Objects have state and behavior.
  90. Question100. 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.
  91. Question101. Stl Containers - What Are The Types Of Stl Containers?
    Answer :
    There are 3 types of STL containers:
    1. Adaptive containers like queue, stack.
    2. Associative containers like set, map.
    3. Sequence containers like vector, deque.
  92. Question102. 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:
    1. dynamic id operator.
    2. typecast operator.
  93. Question103. 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.
  94. Question104. 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.
  95. Question105. 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.
  96. Question106. What Are The Defining Traits Of An Object-oriented Language?
    Answer :
    The defining traits of an object-oriented langauge are:
    • encapsulation,
    • inheritance,
    • polymorphism.
  97. Question107. 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.
  98. Question108. 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.
  99. Question109. 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.
  100. Question110. 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.
  101. Question111. 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.
  102. Question112. 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.
  103. Question113. 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.
  104. Question114. 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.
  105. Question115. 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.
  106. Question116. 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.
  107. Question117. 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.
  108. Question118. 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."
  109. Question119. 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.
  110. Question120. What Is A Conversion Constructor C++?
    Answer :
    A constructor that accepts one argument of a different type.
  111. Question121. 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; }
  112. Question122. 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.
  113. Question123. 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);
  114. Question124. What Are The Differences Between A C++ Struct And C++ Class?
    Answer :
    The default member and base-class access specifiers are different.
  115. Question125. 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.
  116. Question126. How Do You Link A C++ Program To C Functions?
    Answer :
    By using the extern "C" linkage specification around the C function declarations.
  117. Question127. 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); } }
  118. Question128. 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.
  119. Question129. 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
  120. Question130. 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.
  121. Question131. 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.
  122. Question132. 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.
  123. Question133. 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.
  124. Question134. 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.
  125. Question135. 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.
  126. Question136. Anything Wrong With This Code?

    t*p = 0;
    Delete P;

    Answer :
    Yes, the program will crash in an attempt to delete a null pointer.
  127. Question137. 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.
  128. Question138. What Problems Might The Following Macro Bring To The Application?
    Answer :
    #define sq(x) x*x
  129. Question139. 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.
  130. Question140. 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.
  131. Question141. 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.
  132. Question142. 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; };
  133. Question143. 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.
  134. Question144. 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.
  135. Question145. 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.
  136. Question146. What Is Abstraction In C++?
    Answer :
    Abstraction is of the process of hiding unwanted details from the user.
  137. Question147. 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.
  138. Question148. 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.
  139. Question149. 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.
  140. Question150. 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);
  141. Question151. 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.
  142. Question152. 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.
  143. Question153. What Do You Mean By Binding Of Data And Functions?
    Answer :
    Encapsulation.
  144. Question154. 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.
  145. Question155. 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.
  146. Question156. 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.
  147. Question157. 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
  148. Question158. 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.
  149. Question159. 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.
  150. Question160. 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.
  151. Question161. 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.
  152. Question162. 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.
  153. Question163. 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.
  154. Question164. 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.
  155. Question165. 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.
  156. Question166. 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.
  157. Question167. 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.
  158. Question168. 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.
  159. Question169. 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.
  160. Question170. 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.
  161. Question171. 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).
  162. Question172. 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.
  163. Question173. 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.
  164. Question174. 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.
  165. Question175. 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.
  166. Question176. 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.
  167. Question177. 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.
  168. Question178. 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.
  169. Question179. 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.
  170. Question180. 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.
  171. Question181. 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.
  172. Question182. 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.
  173. Question183. 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++.
  174. Question184. 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.
  175. Question185. 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.
  176. Question186. 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.
  177. Question187. 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.
  178. Question188. 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.
  179. Question189. 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.
  180. Question190. 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
  181. Question191. 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.
  182. Question192. 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.
  183. Question193. 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).
  184. Question194. 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.
  185. Question195. 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
  186. Question196. 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.
  187. Question197. 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).
  188. Question198. 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.
  189. Question199. 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.
  190. Question200. 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.
  191. Question201. 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.
  192. Question202. 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.
  193. Question203. 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.
  194. Question204. 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.
  195. Question205. 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.
  196. Question206. 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.
  197. Question207. 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.
  198. Question208. 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.
  199. Question209. 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.
  200. Question210. 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:
    1. An array which can be associated with p in the form of key and a value such as n.
    2. Over-allocation of the array can be done. The preceding techniques are used by the compilers of commercial grade.
  201. Question211. 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:
    1.  Ensure that the allocation of this object is done through new[] operator.
    2. Ensure that the invocation of a member function done on this (current) object will be the last member function.
    3. Ensure that calling of other member functions and data members should not be done after the line of code which includes delete this.
    4. 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.
  202. Question212. 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).
  203. Question213. 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.
  204. Question214. 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.
  205. Question215. 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.
  206. Question216. 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.
  207. Question217. 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.
  208. Question218. 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.
  209. Question219. 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.
  210. Question220. How A Pointer Differs From A Reference?
    Answer :
    A pointer differs from a reference in the following ways:
    1.  In the case of reference, an object must always be referred while initializing. On the contrary, such restrictions are not meant for pointers.
    2. 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.
    3. 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++.
    4.  A reference usually appears outside an object; whereas, a pointer generally appears inside an object.
  211. Question221. 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.
  212. Question222. 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.
  213. Question223. 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 ++().
  214. Question224. 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.
  215. Question225. Provide Some Examples Of Operator Overloading?
    Answer :
    The implementation of operator overloading is done in the following ways:
    1. Concatenating two std:-.string objects by using the + operator
    2.  Incrementing a Date object by using the ++ operator
    3. Multiplying two different number objects by using the * operator
    4. Accessing array elements from an object of the Array class by using the subscript operator
  216. Question226. 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.
  217. Question227. 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.
  218. Question228. 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 [].
  219. Question229. Specify Some Guidelines That Should Be Followed While Overloading Operators?
    Answer :
    Following are some of the guidelines that should be followed while overloading operators:
    1.  Subscript bracket operators should be used for overloading when there is a need of fetching data from the container class.
    2. Arithmetic operators should be used for providing the numerical calculation to the operators.
    3. 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.
    4. The priority order in which operators are executed cannot be modified by overloading the operators.
    5. The overloaded operators must follow the syntax of the language in which they are used.
  220. Question230. 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.
  221. Question231. 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.
  222. Question232. 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.
  223. Question233. 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.
  224. Question234. 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.
  225. Question235. 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:
    1. Make sure that the allocation of this (current) object is done through new [] operator only.
    2. 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.
    3. Make sure that calling of other member functions and data members should not be done after the line of code which includes delete this.
    4. 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.
  226. Question236. 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
  227. Question237. 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.
  228. Question238. 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.
  229. Question239. 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.
  230. Question240. 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.
  231. Question241. 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.
  232. Question242. 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.
  233. Question243. 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 }
  234. Question244. 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.
  235. Question245. 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.
  236. Question246. 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.
  237. Question247. 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.
  238. Question248. 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.
  239. Question249. 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.
  240. Question250. 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.
  241. Question251. 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.
  242. Question252. 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:
    1.  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.
    2. 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++.
    3.  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.
    4.  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.
    5.  In C, the concept of inheritance is not supported. In C++, the concept of inheritance is fully supported.
  243. Question253. 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.
  244. Question254. 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.
  245. Question255. 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.
  246. Question256. 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. For example, the compiler embeds a call to the constructor for each object when it is created. Suppose a class Z has been declared as follows:

    We cannot declare a constructor as virtual or static, nor we can declare a constructor as const, volatile, or const volatile. The short form of constructor is ctor.
  247. Question257. Explain The Concept Of Copy Constructor?
    Answer :
    Copy constructor is a special type of parameterized constructor. It copies one object to another. It is called when an object is created and equated to an existing object at the same time. An existing object is passed as a parameter to it.
  248. Question258. Is It Possible To Pass An Object Of The Same Class In Place Of Object Reference To The Copy Constructor?
    Answer :
    Yes, when an object is created without the reference formal argument, then the copy constructor is called for the argument object. The object that is passed as a parameter to the function is then passed as a parameter to the copy constructor.
    For example:

    In this case, the copy constructor is called for A2 while A1 is passed as a parameter to the copy constructor.
  249. Question259. Define A Conversion Constructor?
    Answer :
    A conversion constructor is a single argument constructor. It is used by the compiler to convert a type of object as an argument to a class type.

    The above example has the following two conversion constructors:
    •  Y(inti)— Helps in the conversion of integers to objects of class Y.
    •  Y(const char* n, int j = 0) —Helps in the conversion of pointers from strings to objects of the Y class
  250. Question260. What Is The Sequence Of Destruction Of Local Objects?
    Answer :
    The destructor is executed in the reverse order of a constructor. Firstly, the objects are constructed, methods are invoked on them, and then they are destructed. In the following example, a's destructor will be executed after b's destructor.
  251. Question261. Explain How Would You Handle A Situation Where You Cannot Call The Destructor Of A Local Explicitly?
    Answer :
    To avoid the explicit calling of a destructor, the time extent of the local variable can be wrapped in an artificial block {...}:
  252. Question262. How Does List R; Differs From List R();?
    Answer :
    Suppose that Member is the name of some class. Then, function f() declares a local member object called r: Example:

    In the preceding code snippet, r is declared as a local variable and the other r() is declared as a function. That is the main difference.
  253. Question263. Define Pure Virtual Function?
    Answer :
    Pure virtual function is defined as a virtual function in a base class. It is implemented 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. A pure virtual function can be created through the following way:
  254. Question264. Write About A Nested Class And Mention Its Use?
    Answer :
    A nested class is a class, defined within the scope of another class. Let's take an example:

    Nested classes are used to organize the codes and control the access of different codes. In the preceding example, if the access specifier is made public for the nested classes, then the name should be classA (outer class):: classD(nested class). If the access specifier is made private, then the nested class can be accessed by the members of the outer class only.
  255. Question265. Write About The Local Class And Mention Its Use?
    Answer :
    A local class is defined as the abstract characteristics of an object, such as attributes, fields, or properties. It also defines the behaviors of objects, such as the methods, operations, or its features. In other words, you can say classes describe objects. A class nested inside the scope of the local helps in managing the codes. Let's take an example:
  256. Question266. Explain The Concept Of Dynamic Allocation Of Memory?
    Answer :
    In C++, memory is divided into three areas, automatic storage (where function's variables are allocated and stored), static storage (where static data is stored and left for the duration of the program's runtime) and the free storage (the memory set for the use of your code at runtime; the new and delete operators are used to allocate and handle space in the free storage).
    Allocating the memory dynamically means that you can allocate space for as many elements as you need at runtime. The memory can be allocated dynamically with the new operator and free with the delete operator. Let's understand it with the help of an example-

    In the preceding code snippet, allocation of memory is done for a double variable, pi, by using the new operator. This operator returns a pointer to a double variable.
  257. Question267. Write A Code Snippet To Display An Integer In A Binary Format?
    Answer :
     

No comments: