InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 201. |
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. 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. |
|
| 202. |
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. A using declaration in C++ makes it possible to use a name from a namespace without the scope operator. |
|
| 203. |
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. 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. |
|
| 204. |
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. 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. |
|
| 205. |
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. 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. |
|
| 206. |
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. 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. |
|
| 207. |
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; } };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: |
|
| 208. |
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: 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: |
|
| 209. |
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.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: |
|
| 210. |
Is It Possible For The Objects To Read And Write Themselves? |
|
Answer» 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. |
|
| 211. |
Using A Smart Pointer Can We Iterate Through A Container? |
|
Answer» 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. |
|
| 212. |
Define A Pointer To A Data Member Of The Type Pointer To Pointer? |
|
Answer» 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 ) ; } |
|
| 213. |
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 ;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. |
|
| 214. |
When Should Overload New Operator On A Global Basis Or A Class Basis? |
|
Answer» 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. |
|
| 215. |
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. Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown below: 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. |
|
| 216. |
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. 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. |
|
| 217. |
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. 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. |
|
| 218. |
What Are Formatting Flags In Ios Class? |
|
Answer» 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. |
|
| 219. |
Write Code To Make An Object Work Like A 2-d Array? |
|
Answer» 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. |
|
| 220. |
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. 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. |
|
| 221. |
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( ). 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( ). |
|
| 222. |
What Is Virtual Multiple Inheritance? |
|
Answer» 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 ; } |
|
| 223. |
What Is A Forward Referencing And When Should It Be Used? |
|
Answer» 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. |
|
| 224. |
Can User-defined Object Be Declared As Static Data Member Of Another Class? |
|
Answer» 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. |
|
| 225. |
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. 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. |
|
| 226. |
Namespaces: |
|
Answer» 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. |
|
| 227. |
Differentiate Between An Inspector And A Mutator ? |
|
Answer» 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. |
|
| 228. |
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. 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. |
|
| 229. |
Why Is That Unsafe To Deal Locate The Memory Using Free( ) If It Has Been Allocated Using New? |
|
Answer» 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. |
|
| 230. |
Assert( ) Macro... |
|
Answer» 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 ; } |
|
| 231. |
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. 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. Here, first we have allocated memory of required size, which then would get deal located through the destructor. |
|
| 232. |
Can I Have A Reference As A Data Member Of A Class? If Yes, Then How Do I Initialise It? |
|
Answer» 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. |
|
| 233. |
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(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. The output of this program would be: |
|
| 234. |
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. 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. |
|
| 235. |
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. 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. |
|
| 236. |
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. No This is because we cannot create an object of the iostream class since its constructor and copy constructorare declared private. |
|
| 237. |
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. 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. |
|
| 238. |
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. To understand this consider following statements, 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. |
|
| 239. |
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. 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. |
|
| 240. |
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. 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. |
|
| 241. |
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. 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. |
|
| 242. |
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. 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. |
|
| 243. |
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. 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. |
|
| 244. |
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. 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. |
|
| 245. |
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» 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( ) ; } |
|
| 246. |
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. This is shown in following code. 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: 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. |
|
| 247. |
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. This is shown in following code snippet. 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. |
|
| 248. |
Carry Out Conversion Of One Object Of User-defined Type To Another? |
|
Answer» 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. |
|
| 249. |
Is It Possible To Provide Default Values While Overloading A Binary Operator? |
|
Answer» 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 } |
|
| 250. |
Refer To A Name Of Class Or Function That Is Defined Within A Namespace? |
|
Answer» 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. |
|