YouTube Icon

Interview Questions.

Top 100+ C++ Interview Questions And Answers - May 28, 2020

fluid

Top 100+ C++ Interview Questions And Answers

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

Answer :

The following program demonstrates this.

#include<stdio.H>
#consist of<iosream>
#encompass<conio.H>
void foremost( )

    int i = 65000 ;
    int *iptr = reinterpret_cast ( i ) ;
    cout << endl << iptr ;
    iptr++ ;
    cout << endl << iptr ;
    i = reinterpret_cast ( iptr ) ;
    cout << endl << i ;
    i++ ;
    cout << endl << i ;

Question 2. What Is Meant By Const_cast?

Answer :

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

#include 
void main( )

     const int a = 0  ;
     int *ptr = ( int * ) &a ; //one way
     ptr = const_cast_ ( &a ) ; //better way

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

class sample

    private:
    int data;
    public:  
      void func( ) const
      
        (const_cast (this))->records = 70 ;
      
;
DBMS Interview Questions
Question three. What Is Meant By Forward Referencing And When Should It Be Used?

Answer :

Forward referencing is usually required when we make a category or a function as a pal.Consider following application:

magnificence check

    public:
        pal void a laugh ( pattern, take a look at ) ;
 ;

class pattern

    public:
        buddy void fun ( pattern, test ) ;
 ;

void fun ( pattern s, check t )

    // code


void principal( )

    sample s ;
    check t ;
    fun ( s, t ) ;

On compiling this software it gives error on the following statement of test elegance. It gives an blunders that pattern is undeclared identifier. Pal void fun ( sample, check ) ; This is so due to the fact the class sample is defined under the elegance take a look at and we're the use of it before its definition. To conquer this mistake we want to present forward reference of the magnificence sample before the definition of class check. The following assertion is the forward reference of class sample.

Elegance pattern;
Question four. Write My Own Zero-argument Manipulator That Should Work Same As Hex?

Answer :This is shown in following application.

#encompass 
ostream& myhex ( ostream &o )

  o.Setf ( ios::hex) ;
  go back o ;

void foremost( )

  cout << endl << myhex << 2000 ;


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

#include<iostream>
Void Main( )

      Const Char *p ;
      P = "a Const Pointer" ;
      Cout << P ;

Answer :

The output of the above program is 'A const pointer'. This is due to the fact on this application p is said as 'const char*' which means that price stored at p will be constant and now not p and so this system works well.

C#. NET Interview Questions
Question 6. Refer To A Name Of Class Or Function That Is Defined Within A Namespace?

Answer :There are  ways wherein we are able to seek advice from a name of sophistication or characteristic this is defined within a namespace: Using scope resolution operator via the the usage of keyword. This is shown in following example:

namespace name1

    magnificence sample1
    
         // code
     ;

namespace name2

     magnificence sample2
     
         // code
      ;

the use of namespace name2 ;
void predominant( )

      name1::sample1 s1 ;
      sample2 s2 ;

Here, class sample1 is referred the use of the scope decision operator. On the alternative hand we are able to immediately consult with magnificence sample2 due to the announcement the use of namespace name2 ; the using keyword broadcasts all of the names in the namespace to be within the present day scope. So we will use the names without any qualifiers.
Question 7. Is It Possible To Provide Default Values While Overloading A Binary Operator?

Answer :No!. This is due to the fact even though we provide the default arguments to the parameters of the overloaded operator characteristic we would turn out to be the usage of the binary operator incorrectly. This is explained within the following example:

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

void essential( )

    pattern s1, s2, s3 ;
    s3 = s1 + ; // errors


                 
C#. NET Tutorial Core Java Interview Questions
Question eight. Carry Out Conversion Of One Object Of User-defined Type To Another?

Answer :To perform conversion from one person-described kind to every other we want to provide conversion characteristic. Following software demonstrates the way to provide such conversion function.

Elegance circle

    private :  
       int radius ;  
       public:  
          circle ( int r = zero )
            
             radius = r ;  
          
 ;
elegance rectangle

     private :
        int period, breadth ;  
        public :  
           rectangle( int l, int b )
             
              period = l ;
              breadth = b ;  
           
           operator circle( )
             
               go back circle ( length ) ;  
             
 ;
void foremost( )
  
    rectangle r ( 20, 10 ) ;
    circle c;
    c = r ;  

Here, while the assertion c = r ; is completed the compiler searches for an overloaded venture operator inside the elegance circle which accepts the object of kind rectangle. Since there is no such overloaded task operator, the conversion operator function that converts the rectangle object to the circle object is searched within the rectangle class. We have furnished one of these conversion function within the rectangle magnificence. This conversion operator function returns a circle item. By default conversion operators have the name and go back kind identical because the item kind to which it converts to. Here the sort of the object is circle and hence the name of the operator function as well as the go back kind is circle.
Question 9. Write Code That Allows To Create Only One Instance Of A Class?

Answer :

This is proven in following code snippet.

#encompass 
class pattern

    static pattern *ptr ;
    non-public:
    pattern( )
    
    
    public:
    static pattern* create( )
    
       if ( ptr == NULL )
          ptr = new sample ;
          return ptr ;
     
 ;
sample *pattern::ptr = NULL ;
void foremost( )

    sample *a = sample::create( ) ;
    sample *b = pattern::create( ) ;

Here, the elegance sample carries a static records member ptr, that's a pointer to the object of equal class. The constructor is private which avoids us from growing items outside the magnificence. A static member feature known as create( ) is used to create an object of the magnificence. In this feature the condition is checked whether or not or no longer ptr is NULL, if it's far then an object is created dynamically and its cope with amassed in ptr is lower back. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one item of pattern gets created whereas on execution of 2d assertion, b holds the cope with of the first item. Thus, whatever range of times you name create( ) characteristic, only one item of sample magnificence might be to be had.

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

Answer :

This is proven in following code.

#encompass 

elegance pattern

   int information ;
   public:
      __declspec ( property ( placed = fun1, get = fun2 ) )
      int x ;
      void fun1 ( int i )
      
         if ( i < zero )
            information = 0 ;
         else
            records = i ;
       
       int fun2( )
       
          go back statistics ;
       
 ;

void important( )

    pattern a ;
    a.X = -99 ;
    cout << a.X ;

Here, the function fun1( ) of class sample is used to set the given integer cost into statistics, whereasfun2( ) returns the cutting-edge price of statistics. To set those capabilities as properties of a class we havegiven the assertion as proven beneath:

 __declspec ( belongings ( positioned = fun1, get = fun2 )) int x ;
As a result, the declaration a.X = -99 ; might purpose fun1( ) to get referred to as to set the fee in information. On the opposite hand, the final declaration would cause fun2( ) to get known as to go back the fee of facts.

Core Java Tutorial
Question eleven. Write A Program That Implements A Date Class Containing Day, Month And Year As Data Members. Implement Assignment Operator And Copy Constructor In This Class.

Answer :This is proven in following application:

#consist of 

magnificence date

     private :
        int day ;
        int month ;
        int yr ;
     public :
        date ( int d = zero, int m = 0, int y = zero )
        
            day = d ;
            month = m ;
            yr = y ;
        
        // reproduction constructor
        date ( date &d )
        
            day = d.Day ;
            month = d.Month ;
            12 months = d.Year ;  
        
        // an overloaded task operator
        date operator = ( date d )
        
            day = d.Day ;
            month = d.Month ;
            12 months = d.Yr ;
            go back d ;  
        
        void show( )
        
            cout << day << "/" << month << "/" << year ;
        
 ;
void main( )

        date d1 ( 25, 9, 1979 ) ;
        date d2 = d1 ;
        date d3 ;
        d3 = d2 ;
        d3.Display( ) ;

C & Data Structures Interview Questions
Question 12. When Should I Use Unitbuf Flag?

Answer :

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

DBMS Interview Questions
Question 13. What Are Manipulators?

Answer :

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

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

Answer :

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

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

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

Answer :

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

ADO.Net Interview Questions
Question 16. What Are Put And Get Pointers?

Answer :

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

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

Answer :

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

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

Answer :

To understand this consider following statements,

       char str[5] ;
cin >> str ;
While coming into the fee for str if we input more than five characters then there's no provision in cin to check the array bounds. If the array overflows, it is able to be dangerous. This may be averted by using get( ) function. For example, take into account following statement,cin.Get ( str, five ) ; On executing this statement if we enter extra than 5 characters, then get( ) takes simplest first five characters and ignores relaxation of the characters. Some greater variations of get( ) are to be had, along with shown beneath:

get ( ch ) - Extracts one man or woman handiest get ( str, n ) - Extracts up to n characters into str get ( str, DELIM ) - Extracts characters into array str until detailed delimiter (such as 'n'). Leaves delimiting character in movement.

Get ( str, n, DELIM ) - Extracts characters into array str till n characters or DELIM person, leaving delimiting character in movement.

C#. NET Interview Questions
Question 19. Mention The Purpose Of Istream Class?

Answer :

The istream magnificence plays sports precise to input. It is derived from the iosclass. The most usually used member feature of this class is the overloaded >> operator which canextract values of all primary kinds. We can extract even a string the use of this operator.

Go (programming language) Tutorial
Question 20. Would The Following Code Work?

 #consist of<iosteram.>
Void Main( )
 
 Ostream O ;
 O << "dream. Then Make It Happen!" ;

Answer :

No This is because we cannot create an object of the iostream elegance when you consider that its constructor and duplicate constructorare declared personal.

Go (programming language) Interview Questions
Question 21. Can We Use This Pointer Inside Static Member Function?

Answer :

No! The this pointer can't be used inside a static member function. This is due to the fact a static member function is never called via an item.

Question 22. What Is Strstream?

Answer :

strstream is a type of enter/output circulate that works with the memory. It permits the use of section of the memory as a stream item. These streams provide the instructions that can be used for storing the movement of bytes into memory. For instance, we will shop integers, floats and strings as a move of bytes. There are numerous classes that put into effect this in-memory formatting. The class ostrstream derived from ostream is used when output is to be sent to memory, the magnificence istrstream derived from istream is used when enter is taken from memory and strstream magnificence derived from iostream is used for reminiscence objects that do each input and output.

F Sharp (programming language) Tutorial
Question 23. When The Constructor Of A Base Class Calls A Virtual Function, Why Doesn't The Override Function Of The Derived Class Gets Called?

Answer :

While building an item of a derived class first the constructor of the bottom class and then the constructor of the derived class gets referred to as. The item is stated an immature object on the stage whilst the constructor of base magnificence is called. This object will be called a matured object after the execution of the constructor of the derived elegance. Thus, if we call a digital characteristic whilst an item continues to be immature, glaringly, the digital characteristic of the base elegance might get known as. This is illustrated in the following instance.

#include 

magnificence base

   included :
     int i ;
     public :
       base ( int ii = 0 )
       
           i = ii ;
           display( ) ;
       

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

elegance derived : public base

      personal :
        int j ;
      public :
        derived ( int ii, int jj = zero ) : base ( ii )
        
           j = jj ;
           display( ) ;
        
       void display( )
       
           cout << "derived's show( )" << endl ;
       
 ;
                               
void essential( )

   derived dobj ( 20, 5 ) ;

The output of this software would be:

base's show( )
derived's show( 
F Sharp (programming language) Interview Questions
Question 24. Can I Have A Reference As A Data Member Of A Class? If Yes, Then How Do I Initialise It?

Answer :Yes, we will have a reference as a information member of a category. A reference as a records member of a category is initialised within the initialisation listing of the constructor. This is shown in following program.

#include 
elegance pattern

   non-public :
     int& i ;
     public :
       sample ( int& ii ) : i ( ii )
       
       
       void display( )
       
         cout << i << endl ;
       
 ;

void fundamental( )

  int j = 10 ;
  pattern s ( j ) ;
  s.Display( ) ;

Here, i refers to a variable j allotted on the stack. A point to observe here is that we can't bind a reference to an item passed to the constructor as a fee. If we achieve this, then the reference i would refer to the function parameter (i.E. Parameter ii inside the constructor), which might disappear as soon because the feature returns, thereby growing a situation of dangling reference.
Core Java Interview Questions
Question 25. Why Does The Following Code Fail?

#include<iostream.>
#encompass<string.H> 
Class Sample

Private :char *str ;
Public : Sample ( Char *s )

Strcpy ( Str, S ) ;

~sample( )

Delete Str ;

 ;
Void Main( )

Sample S1 ( "abc" ) ;

Answer :

Here, thru the destructor we're seeking to deal find reminiscence, which has been allocated statically. To remove an exception, upload following assertion to the constructor.

Sample ( char *s )

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

Here, first we have allotted memory of required length, which then would get deal placed via the destructor.

R Programming language Tutorial
Question 26. Assert( ) Macro...

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

#consist of 
#include 
void essential( )

   int i ;
   cout << "nEnter an integer: " ;
   cin >> i ;
   assert ( i >= zero ) ;
   cout << i << endl ;

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

Answer :This can be defined with the subsequent instance:

#consist of 
class sample

  int *p ;
  public :
     sample( )
     
       p = new int ;
     

     ~pattern( )
     
        delete p ;
     
 ;

void foremost( )

  pattern *s1 = new pattern ;
  free ( s1 ) ;
  pattern *s2 = ( pattern * ) malloc ( sizeof ( pattern ) ) ;
  delete s2 ;

The new operator allocates reminiscence and calls the constructor. In the constructor we've got allotted reminiscence on heap, that's pointed to via p. If we release the item the use of the free( ) characteristic the item would die but the reminiscence allotted in the constructor could leak. This is due to the fact free( ) being a C library feature does not call the destructor where we have deal located the memory.
As towards this, if we allocate reminiscence with the aid of calling malloc( ) the constructor could now not get called. Hence p holds a garbage cope with. Now if the memory is deal placed the use of delete, the destructor could get referred to as wherein we've attempted to launch the reminiscence pointed to through p. Since p carries rubbish this may bring about a runtime errors.

Data Structures Interview Questions
Question 28. Can We Distribute Function Templates And Class Templates In Object Libraries?

Answer :

No! We can bring together a feature template or a class template into object code (.Obj file). The code that carries a call to the characteristic template or the code that creates an object from a class template can get compiled. This is due to the fact the compiler simply checks whether or not the call fits the declaration (in case of feature template) and whether the object definition suits magnificence declaration (in case of class template). Since the characteristic template and the class template definitions aren't discovered, the compiler leaves it to the linker to restore this. However, throughout linking, linker does not locate the matching definitions for the characteristic call or a matching definition for item advent. In short the accelerated versions of templates are not found in the object library. Hence the linker reports error.

D Programming Language Tutorial
Question 29. Differentiate Between An Inspector And A Mutator ?

Answer :An inspector is a member feature that returns data about an object's state (records saved in item's statistics contributors) without changing the object's nation. A mutator is a member feature that modifications the kingdom of an object. In the magnificence Stack given underneath we've described a mutator and an inspector.

Magnificence Stack

   public :
   int pop( ) ;
   int getcount( ) ;

In the above instance, the feature pop( ) removes top element of stack thereby converting the kingdom of an item. So, the characteristic pop( ) is a mutator. The function getcount( ) is an inspector because it in reality counts the number of factors inside the stack without converting the stack.
R Programming language Interview Questions
Question 30. Namespaces:

Answer :The C++ language affords a single international namespace. This can reason issues with worldwide name clashes. For example, bear in mind those  C++ header files: // file1.H waft f ( waft, int ) ; magnificence pattern  ...  ; // file2.H magnificence sample  ...  ; With those definitions, it's far impossible to apply both header documents in a unmarried application; the sample training will conflict.A namespace is a declarative vicinity that attaches an extra identifier to any names declared inner it. The extra identifier as a result avoids the opportunity that a name will struggle with names declared someplace else in the software. It is viable to apply the identical name in separate namespaces with out battle even if the names appear within the same translation unit. As lengthy as they appear in separate namespaces, every call might be particular due to the addition of the namespace identifier. For instance:

// file1.H
namespace file1

   flow f ( go with the flow, int ) ;
   elegance sample  ...  ;

// file2.H
namespace file2

    elegance sample  ...  ;

Now the magnificence names will now not conflict because they end up file1::pattern and file2::pattern, respectively.
Question 31. Declare A Static Function As Virtual?No. The Virtual Function Mechanism Is Used On The Specific Object That Determines Which Virtual Function To Call. Since The Static Functions Are Not Any Way Related To Objects, They Cannot Be Declared As Virtual.

Answer :

No. The virtual feature mechanism is used on the particular item that determines which digital feature to call. Since the static features aren't any way associated with items, they can not be declared as digital.

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

Answer :Yes. The following code shows how to initialize a consumer-described item.

#include 
class check

  int i ;  
  public :
    test ( int ii = zero )
    
      i = ii ;  
    
 ;
class pattern

  static test s ;
 ;
check pattern::s ( 26 ) ;
Here we have initialized the object s with the aid of calling the one-argument constructor. We can use the same conference to initialize the object by calling more than one-argument constructor.
D Programming Language Interview Questions
Question 33. What Is A Forward Referencing And When Should It Be Used?

Answer :Consider the following application:

magnificence test

   public :
     pal void a laugh ( pattern, check ) ;  
 ;

class sample

   public :
     buddy void amusing ( pattern, test ) ;
 ;

void a laugh ( pattern s, check t )

   // code  


void main( )

   sample s ;
   check t ;
   fun ( s, t ) ;

This program would not assemble. It offers an error that sample is undeclared identifier inside the statement pal void fun ( sample, take a look at ) ; of the magnificence take a look at. This is so because the class sample is defined beneath the class check and we're using it before its definition. To overcome this mistake we want to provide forward reference of the magnificence pattern earlier than the definition of class test. The following statement is the ahead reference of sophistication pattern. Forward referencing is usually required whilst we make a class or a feature as a chum.
C & Data Structures Interview Questions
Question 34. What Is Virtual Multiple Inheritance?

Answer :A magnificence b is defined having member variable i. Suppose  lessons d1 and d2 are derived from magnificence b and a category a couple of is derived from each d1 and d2. If variable i is accessed from a member feature of multiple then it gives errors as 'member is ambiguous'. To avoid this error derive lessons d1 and d2 with modifier virtual as shown in the following software.

#encompass 
magnificence b

  public :
    int i ;
  public :
    fun( )
    
      i = zero ;
    
 ;
class d1 : digital public b

  public :
    fun( )
    
      i = 1 ;
    
 ;
class d2 : digital public b

  public :
    amusing( )
    
      i = 2 ;
    
 ;
elegance multiple : public d1, public d2

  public :
    fun( )
    
      i = 10 ;
    
 ;
void primary( )

   a couple of d ;
   d.A laugh( ) ;
   cout << d.I ;

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

Answer :

No! The this pointer is in no way exceeded to the overloaded operator new() member characteristic because this function receives known as before the item is created. Hence there may be no question of the this pointer getting handed to operator new( ).

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

Answer :

No! It isn't possible to allocate memory dynamically for a reference. This is because, while we create a reference, it gets tied with a few variable of its type. Now, if we strive to allocate memory dynamically for a reference, it is not feasible to say that to which variable the reference might get tied.

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

Answer :Take a have a look at the following application.

#consist of 
magnificence emp

  public :
    int a[3][3] ;
    emp( )
    
      int c = 1 ;
      for ( int i = zero ; i <= 2 ; i++ )
      
         for ( int j = zero ; j <= 2 ; j++ )
         
           a[i][j] = c ;
           c++ ;
         
       
     
     int* operator[] ( int i )
     
       return a[i] ;
     
 ;
void important( )

  emp e ;
  cout << e[0][1] ;

The magnificence emp has an overloaded operator [ ] feature. It takes one argument an integer representing an array index and returns an int pointer. The announcement cout << e[0][1] ; might get converted right into a name to the overloaded [ ] feature as e.Operator[ ] ( zero ). 0 might get collected in i. The feature could return a[i] that represents the bottom deal with of the zeroeth row. Next the announcement could get multiplied as base deal with of zeroeth row[1] that can be similarly elevated as *( base address + 1 ). This gives us a fee in zeroth row and first column.
Question 38. What Are Formatting Flags In Ios Class?

Answer :The ios class incorporates formatting flags that help customers to layout the stream records. Formatting flags are a hard and fast of enum definitions. There are two types of formatting flags:On/Off flagsFlags that work in-organization The On/Off flags are turned on the usage of the setf( ) function and are became off the usage of the unsetf( )function. To set the On/Off flags, the only argument setf( ) function is used. The flags working in corporations are set via the two-argument setf( ) characteristic. For instance, to left justify a string we can set the flag as,

cout.Setf ( ios::left );
cout << "KICIT Nagpur";
To eliminate the left justification for next output we can say,
cout.Unsetf ( ios::left );
The flags that can be set/unset encompass skipws, showbase, showpoint, uppercase, showpos, unitbufand stdio. The flags that work in a collection could have only this kind of flags set at a time.
Question 39. What Is The Purpose Of Ios::basefield In The Following Statement?

Cout.Setf ( Ios::hex, Ios::basefield );
Answer :

This is an instance of formatting flags that work in a set. There is a flag for every numbering gadget (base) like decimal, octal and hexadecimal. Collectively, these flags are called basefield and are targeted by means of ios::basefield flag. We may have most effective such a flags on at a time. If we set the hex flag as setf ( ios::hex ) then we can set the hex bit however we might not clear the dec bit ensuing in undefined behavior. The solution is to name setf( ) as setf ( ios::hex, ios::basefield ). This call first clears all of the bits and then sets the hex bit.

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

Answer :

Yes! The ios::flags( ) member function gives the value layout flags. This characteristic takes no arguments and returns a protracted ( typedefed to fmtflags) that contains the contemporary layout flags.

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

Answer :

Yes! This may be achieved using cin::forget about( ) function. The prototype of this characteristic is as proven under:

istream& forget about ( int n = 1, int d =EOF );
Sometimes it happens that some extra characters are left inside the enter movement even as taking the enter which includes, the 'n' (Enter) person. This more individual is then surpassed to the subsequent input and can pose hassle.

To take away such greater characters the cin::forget about( ) feature is used. This is equal to fflush ( stdin ) used in C language. This function ignores the primary n characters (if present) within the enter stream, stops if delimiter d is encountered.

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

Answer :We overload operator new in our software, while we need to initialize a information item or a category item at the identical area in which it has been allocated memory. The following example indicates how to overload new operator on worldwide foundation.

#consist of 
#include 
void * operator new ( size_t s )

   void *q = malloc ( s ) ;
   go back q ;

void primary( )

  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 ;
       go back q ;
     
 ;
elegance sample1

   flow f ;  
   public :
   void* operator new ( size_t s, drift ff )
   
     sample1 *q = ( sample1 * ) malloc ( s ) ;
     q -> f = ff ;
     return q ;
   
  ;
void fundamental( )

  sample *s = new ( 7 ) pattern ;
  sample1 *s1 = new ( 5.6f ) sample1 ;

Overloading the operator new on elegance-by using-class basis makes it viable to allocate memory for an item and initialize its statistics individuals at the identical place.
Go (programming language) Interview Questions
Question forty three. How To Give An Alternate Name To A Namespace?

Answer :

An exchange name given to namespace is referred to as a namespace-alias. Namespace-alias is generally used to save the typing attempt while the names of namespaces are very long or complex. The following syntax is used to offer an alias to a namespace.

Namespace myname = my_old_very_long_name ;
Question 44. Define A Pointer To A Data Member Of The Type Pointer To Pointer?

Answer :The following software demonstrates this...

#consist of 
magnificence sample

  public :
    pattern ( int **pp )
    
      p = pp ;
    
    int **p ;
 ;
int **pattern::*ptr = &pattern::p ;
void primary( )

  int i = 9 ;
  int *pi = &i ;
  sample s ( π ) ;
  cout << ** ( s.*ptr ) ;

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

Answer :Yes. A container is a group of elements or gadgets. It enables to correctly arrange and shop the information. Stacks, related lists, arrays are examples of bins. Following software suggests the way to iterate through a container the use of a clever pointer.

#encompass 
elegance smartpointer

  personal :
     int *p ; // regular pointer
     public :
     smartpointer ( int n )
     
       p = new int [ n ] ;
       int *t = p ;
       for ( int i = 0 ; i <= nine ; i++ )
         *t++ = i * i ;
     
     int* operator ++ ( int )
     
       go back p++ ;
     
     int operator * ( )
     
       return *p ;
     
 ;
void foremost( )

   smartpointer sp ( 10 ) ;
   for ( int i = 0 ; i <= nine ; i++ )
     cout << *sp++ << endl ;

Here, sp is a clever pointer. When we say *sp, the operator * ( ) feature receives referred to as. It returns the integer being pointed to by way of p. When we are saying sp++ the operator ++ ( ) function receives referred to as. It increments p to factor to the following element inside the array after which returns the address of this new region.
Question forty six. Is It Possible For The Objects To Read And Write Themselves?

Answer :Yes! This can be defined with the assist of following example:

#consist of 
#consist of 
magnificence employee

  private :
     char name [ 20 ] ;
     int age ;
     waft revenue ;
     public :
     void getdata( )
     
       cout << "Enter name, age and salary of employee : " ;
       cin >> name >> age >> profits ;
     
     void keep( )
     
       ofstream record ;
       report ios::binary ) ;
       record.Write ( ( char * ) this, sizeof ( *this ) ) ;
       report.Close( ) ;
     
     void retrieve ( int n )
     
       ifstream record ;
       record.Open ( "EMPLOYEE.DAT", ios::binary ) ;
       report.Seekg ( n * sizeof ( worker ) ) ;
       document.Read ( ( char * ) this, sizeof ( *this ) ) ;
       document.Near( ) ;
     
     void show( )
     
       cout << "Name : " << call
       << endl << "Age : " << age
       << endl << "Salary :" << earnings << endl ;
     
 ;
void predominant( )

   worker e [ 5 ] ;
   for ( int i = zero ; i <= four ; i++ )
   
     e [ i ].Getdata( ) ;
     e [ i ].Keep( ) ;
   
   for ( i = zero ; i <= 4 ; i++ )
   
     e [ i ].Retrieve ( i ) ;
     e [ i ].Show( ) ;
   

Here, employee is the magnificence whose gadgets can write and study themselves. The getdata( ) feature has been used to get the statistics of worker and store it inside the facts members name, age and revenue. The keep( ) feature is used to write down an object to the document. In this function a report has been opened in append mode and on every occasion records of cutting-edge item has been saved after the last document (if any) in the document.Function retrieve( ) is used to get the records of a particular worker from the document. This retrieved facts has been saved within the facts individuals name, age and salary. Here this has been used to keep facts because it consists of the cope with of the modern object. The feature display( ) has been used to show the facts of worker.
Question 47. Why Is It Necessary To Use A Reference In The Argument To The Copy Constructor?

Answer :

If we bypass the copy constructor the argument via cost, its replica would get constructed using the copy constructor. This method the replica constructor would call itself to make this copy. This process could pass on and on till the compiler runs out of reminiscence. This can be explained with the assist of following instance:

elegance sample

   int i ;
   public :
   sample ( sample p )
   
     i = p.I ;
   
 ;
void major( )

   sample s ;
   pattern s1 ( s ) ;

While executing the announcement pattern s1 ( s ), the replica constructor would get known as. As the reproduction construct here accepts a value, the fee of s could be surpassed which might get accrued in p. We can think of this assertion as pattern p = s. Here p is getting created and initialized. Means once more the reproduction constructor could get referred to as. This might result into recursive calls. Hence we should use a reference as an argument in a duplicate constructor.
Question forty eight. What Is C++?

Answer :

Released in 1985, C++ is an item-oriented programming language created by means of Bjarne Stroustrup. C++ continues nearly all factors of the C language, even as simplifying memory control and including several capabilities - such as a new datatype referred to as a category (you'll analyze greater approximately these later) - to permit item-oriented programming. C++ continues the capabilities of C which allowed for low-stage reminiscence get right of entry to but additionally offers the programmer new gear to simplify reminiscence control.

C++ used for:
C++ is a powerful widespread-purpose programming language. It can be used to create small programs or large programs. It can be used to make CGI scripts or console-best DOS packages. C++ allows you to create packages to do almost something you want to do. The author of C++, Bjarne Stroustrup, has prepare a partial list of programs written in C++.

Question forty nine. What Is A Modifier In C++?

Answer :

A modifier, additionally called a modifying characteristic is a member function that adjustments the fee of as a minimum one data member. In other phrases, an operation that modifies the country of an object. Modifiers are also referred to as 'mutators'. Example: The function mod is a modifier in the following code snippet:

magnificence test

int  x,y;
public:
check()

x=0; y=0;

void mod()
  x=10;
y=15;  

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

Answer :

An accessor is a class operation that doesn't regulate the kingdom of an item in C++. The accessor functions want to be declared as const operations.

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

Answer :

Template magnificence:  A regularly occurring definition or a parameterized elegance now not instantiated until the client gives the wanted facts. It's jargon for plain templates.

Class template: A magnificence template specifies how man or woman lessons can be built similar to the manner a category specifies how man or woman items can be built. It's jargon for undeniable training.

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

Answer :

A name conflict occurs whilst a call is described in a couple of place. For example., two specific elegance libraries could provide two specific classes the same name. If you try to use many elegance libraries at the identical time, there may be a truthful threat that you may be not able to assemble or hyperlink this system because of name clashes.

Question 53. Define Namespace In C++?

Answer :

It is a feature in C++ to reduce call collisions inside the global name area. This namespace key-word assigns a wonderful name to a library that lets in different libraries to apply the same identifier names without growing any call collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.

Question fifty four. What Is The Use Of 'the use of' Declaration In C++?

Answer :

A the usage of announcement in C++ makes it feasible to use a name from a namespace without the scope operator.

Question fifty five. What Is An Iterator Class In C++?

Answer :

A magnificence this is used to traverse via the objects maintained by way of a box class. There are five classes of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random get admission to. An iterator is an entity that gives get admission to to the contents of a field item with out violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis so as. The order may be storage order (as in lists and queues) or a few arbitrary order (as in array indices) or in line with a few ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, whilst referred to as, yields both the following detail within the field, or a few cost denoting the reality that there are not any more elements to look at. Iterators disguise the details of get right of entry to to and replace of the factors of a field class. The most effective and safest iterators are people who allow study-most effective get right of entry to to the contents of a box class.

Question fifty six. What Is An Incomplete Type In C++?

Answer :

Incomplete kinds refers to recommendations wherein there's non availability of the implementation of the referenced vicinity or it points to a few vicinity whose cost isn't always available for change.

Int *i=0x400    //i points to address four hundred
*i=0;          //set the  value of memory location pointed by way of i.
Incomplete sorts are otherwise known as uninitialized suggestions.

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

Answer :

A dangling pointer arises whilst you use the cope with of an object after its lifetime is over. This might also arise in situations like returning addresses of the automated variables from a characteristic or using the deal with of the reminiscence block after it is freed. The following code snippet suggests this:

class Sample

public:int *ptr; Sample(int i)

ptr = new  int(i);

~Sample()

delete ptr;

void PrintValO

cout« "The price is " « *ptr;

;
void SomeFunc(Sample  x)

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

int foremost()

Sample si = 10;
SomeFunc(sl);
sl.PrintVal();

In the above example when PrintVal() function is known as it's far known as by the pointer that has been freed through the destructor in SomeFunc.

 

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

Answer :

Message in C++ :

Objects communicate by means of sending messages to every different.
A message is despatched to invoke a technique in C++.
Method in C++ :

Provides response to a message.
It is an implementation of an operation in C++.
Question fifty nine. What Is An Adaptor Class Or Wrapper Class In C++?

Answer :

A elegance that has no capability of its personal is an Adaptor class in C++. Its member capabilities hide the use of a 3rd birthday party software program issue or an item with the non-like minded interface or a non-object-oriented implementation.

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

Answer :

It is an object of a few class whose reason is to indicate that a actual item of that class does now not exist. One not unusual use for a null item is a go back value from a member feature that is meant to go back an item with some specified properties however cannot locate such an item.

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

Answer :

A class invariant is a condition that defines all legitimate states for an object. It is a logical condition to make certain the precise operating of a class. Class invariants have to preserve when an object is created, and they have to be preserved below all operations of the magnificence. In specific all class invariants are each preconditions and publish-situations for all operations or member capabilities of the magnificence.




CFG