Vous êtes sur la page 1sur 20

C & C++

1. #include<stdio.h> main() { const int i=4; float j; j = ++i; printf("%d %f", i,++j); } Answer: Compiler error Explanation: i is a constant. you cannot change the value of constant 2. void main() { int const * p=5; printf("%d",++(*p)); } Answer: Compiler error: Cannot modify a constant value. Explanation: p is a pointer to a "constant integer". But we tried to change the value of the "constant integer". 3. main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); } Answer: mmmm aaaa nnnn Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].

4. main() { float me = 1.1; double you = 1.1; if(me==you) printf("I love U"); else printf("I hate U"); } Answer: I hate U Explanation: For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double. Rule of Thumb: Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) 5. main() { static int var = 5; printf("%d ",var--); if(var) main(); } Answer: 54321 Explanation: When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively. 6. What is the difference between a NULL pointer and a void pointer? Ans: A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does).

7. What is difference between C++ and Java? Ans: C++ has pointers Java does not.

Java is platform independent C++ is not. Java has garbage collection C++ does not. 8. What do you mean by multiple inheritance in C++ ? Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teaching Assistant is inherited from two classes say teacher and Student. 9. What do you mean by virtual methods? Ans: virtual methods are used to use the polymorphism feature in C++. Say class A is inherited from class B. If we declare say function f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.

10. What do you mean by static methods? Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A. 11. How many ways are there to initialize an int with a constant? Ans: Two. There are two formats 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); 12. What is a constructor? Ans: Constructor is a special member function of a class, which is invoked automatically whenever an instance of the class is created. It has the same name as its class. 13. What is destructor? Ans: Destructor is a special member function of a class, which is invoked automatically whenever an object goes out of the scope. It has the same name as its class with a tilde character prefixed. 14. What is an explicit constructor? Ans: A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. Its purpose is reserved explicitly for construction. 15 What is the Standard Template Library? Ans: 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. 16 Name the operators that cannot be overloaded? Ans: sizeof, ., .*, .->, ::, ?: 17. What is an adaptor class or Wrapper class? Ans: A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non-objectoriented implementation. 18. What is a Null object? Ans: 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. 19. What is class invariant? Ans: 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. 20. What is a dangling pointer? Ans: 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. Example: The following code snippet shows this: class Sample { public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; } void PrintVal() { cout << The value is << *ptr; } }; void SomeFunc(Sample x)

{ cout << Say i am in someFunc << endl; } int main() { Sample s1= 10; SomeFunc(s1); s1.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. 21. Differentiate between the message and method? Ans: Message: Objects communicate by sending messages to each other. A message is sent to invoke a method. Method: Provides response to a message and it is an implementation of an operation 22. How can we access protected and private members of a class? Ans: In the case of members protected and private, these could not be accessed from outside the same class at which they are declared. This rule can be transgressed with the use of the friend keyword in a class, so we can allow an external function to gain access to the protected and private members of a class. 23. Can you handle exception in C++? Ans: Yes we can handle exception in C++ using keyword: try, catch and throw. Program statements that we want to monitor for exceptions are contained in a try block. If an exception occurs within the try block, it is thrown (using throw).The exception is caught, using catch, and processed. 24. What is virtual function? Ans: A virtual function is a member function that is declared within a base class and redefined by a derived class .To create a virtual function, the function declaration in the base class is preceded by the keyword virtual. 25. What do you mean by early binding? Ans:Early binding refers to the events that occur at compile time. Early binding occurs when all information needed to call a function is known at compile time. Examples of early binding include normal function calls, overloaded function calls, and overloaded operators. The advantage of early binding is efficiency. 26. What do you mean by late binding? Ans: Late binding refers to function calls that are not resolved until run time. Virtual functions are used to achieve late binding. When access is via a base pointer or reference, the virtual function actually called is determined by the type of object pointed to by the pointer.

27.What problem does the namespace feature solve? Ans: 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 librarys external declarations with a unique namespace that eliminates the potential for those collisions. This solution assumes that two library vendors dont use the same namespace identifier, of course. 28. What is the use of using declaration? Ans: A using declaration makes it possible to use a name from a namespace 29. What is a template? Ans: Templates allow us 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. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones: template function_declaration; template function_declaration; 30. Differentiate between a template class and class template? Ans: Template class: A generic definition or a parameterized class not instantiated until the client provides the needed information. Its 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. Its jargon for plain classes. 31. What is the difference between a copy constructor and an overloaded assignment operator? Ans: 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. 32. What is a virtual destructor? Ans: The simple answer is that a virtual destructor is one that is declared with the virtual attribute. 33. What is an incomplete type? Ans: Incomplete type 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. Example: int *i=0400 // i points to address 400 *i=0; //set the value of memory location pointed by i. Incomplete types are otherwise called uninitialized pointers. 34. What do you mean by Stack unwinding? Ans: It 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.

35. What is a container class? What are the types of container classes? Ans: 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 wellknown 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 36. Name some pure object oriented languages? Ans: Smalltalk, Java, Eiffel, Sather. 37. What will print out? main() { char *p1=name; char *p2; p2=(char*)malloc(20); memset (p2, 0, 20); while(*p2++ = *p1++); printf(%sn,p2); } Answer:empty string. 38. What will be printed as the result of the operation below: main() { int x=20,y=35; x=y++ + x++; y= ++y + ++x; printf(%d%dn,x,y); } Answer : 5794 39 What will be printed as the result of the operation below: main() { int x=5; printf(%d,%d,%dn,x,x< <2,x>>2); }

Answer: 5,20,1 40 What will be printed as the result of the operation below: #define swap(a,b) a=a+b;b=a-b;a=a-b; void main() { int x=5, y=10; swap (x,y); printf(%d %dn,x,y); swap2(x,y); printf(%d %dn,x,y); } int swap2(int a, int b) { int temp; temp=a; b=a; a=temp; return 0; } Answer: 10, 5 10, 5 41. What will be printed as the result of the operation below: main() { char *ptr = Cisco Systems; *ptr++; printf(%sn,ptr); ptr++; printf(%sn,ptr); } Answer:Cisco Systems isco systems 42 What will be printed as the result of the operation below: main() { char s1[]=Cisco; char s2[]= systems;

printf(%s,s1); } Answer: Cisco 43 What will be printed as the result of the operation below: main() { char *p1; char *p2; p1=(char *)malloc(25); p2=(char *)malloc(25); strcpy(p1,Cisco); strcpy(p2,systems); strcat(p1,p2); printf(%s,p1); } Answer: Ciscosystems 44 .The following variable is available in file1.c, who can access it?: static int average; Answer: all the functions in the file1.c can access the variable. 45. WHat will be the result of the following code? #define TRUE 0 // some code while(TRUE) { // some code } Answer: This will not go into the loop as TRUE is defined as 0. 46. What will be printed as the result of the operation below: int x; int modifyvalue() {

return(x+=10); } int changevalue(int x) { return(x+=1); } void main() { int x=10; x++; changevalue(x); x++; modifyvalue(); printf("First output:%dn",x); x++; changevalue(x); printf("Second output:%dn",x); modifyvalue(); printf("Third output:%dn",x); } Answer: 12 , 13 , 13 47. What will be printed as the result of the operation below: main() { int x=10, y=15; x = x++; y = ++y; printf(%d %dn,x,y); } Answer: 11, 16 48. What will be printed as the result of the operation below: main() { int a=0; if(a==0) printf(Cisco Systemsn); printf(Cisco Systemsn);

} Answer: Two lines with Cisco Systems will be printed. 49. When are copy constructors called? Copy constructors are called in following cases: a) when a function returns an object of that class by value b) when the object of that class is passed by value as an argument to a function c) when you construct an object based on another object of the same class d) When compiler generates a temporary object 50. What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don't define one.?? default ctor copy ctor assignment operator default destructor address operator 51. What is difference between template and macro?? There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking. If macro parameter has a postincremented variable ( like c++ ), the increment is performed two times. Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging. 52. What are C++ storage classes? Ans: auto register static extern auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance

static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined. 53. What are storage qualifiers in C++ ? Ans: They are.. const volatile mutable Const keyword indicates that memory once initialized, should not be altered by a program. volatile keyword indicates that the value in the memory location can be altered even though nothing in the program code modifies the contents. for example if you have a pointer to hardware location that contains 1the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler. mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant. 54. What is reference ?? Ans: reference is a name that acts as an alias, or alternative name, for a previously defined variable or an object. prepending variable with "&" symbol makes it as reference. for example: int a; int &b = a;

55. What is passing by reference? Ans: Method of passing arguments to a function which takes parameter of type reference. for example:

void swap( int & x, int & y ) { int temp = x; x = y; y = temp; } int a=2, b=3; swap( a, b ); Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.

56. When do use "const" reference arguments in function? Ans: a) Using const protects you against programming errors that inadvertently alter data. b) Using const allows function to process both const and non-const actual arguments, while a function without const in the prototype can only accept non constant arguments. c) Using a const reference allows the function to generate and use a temporary variable appropriately.

57. What is virtual function? Ans: When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.

58. What is pure virtual function? or what is abstract class? Ans: When you define only function prototype in a base class without implementation and do the complete implementation in derived class. This base class is called abstract class and client won't able to instantiate an object using this base class. 59. What problem does the namespace feature solve? Ans: 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.

60. What is overloading?? Ans: With the C++ language, you can overload functions and operators. Overloading is the practice of supplying more than one definition for a given function name in the same scope. - Any two functions in a set of overloaded functions must have different argument lists. - Overloading functions with argument lists of the same types, based on return type alone, is an error. 61. What is Overriding? Ans: 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. The definition of the method overriding is: Must have same method name. Must have same data type. Must have same argument list. Overriding a method means that replacing a method functionality in child class. To imply overriding functionality we need parent and child classes. In the child class you define the same method signature as one defined in the parent class. 62. What is the difference between a pointer and a reference? Ans: A reference must always refer to some object and, therefore, must always be initialized; pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized.

63. What is the difference between realloc() and free()? Ans: 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. 64. What is public, protected, private? Ans: Public, protected and private are three access specifier 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 cant be accessed outside the class. However there is an exception can be using friend classes. 65. What is namespace? Ans: Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces. 66. What is virtual class and friend class? Ans: 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. 67. What is a scope resolution operator? Ans: A scope resolution operator (::), can be used to define the member functions of a class outside the class. 68. What is polymorphism? Explain with an example? Ans: "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 69. main() { int i=3; switch(i) { default:printf("zero"); case 1: printf("one"); break; case 2:printf("two"); break; case 3: printf("three"); break; } } Answer : three Explanation : The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match. 70 : f = fopen(filename,"r"); refering to the code above, what is the proper definition for the variable f? Ans: File *f;

71. char txt [20] = "hello world\0"; how many bytes are allocated by teh definition above ? Ans : 20 bytes 72. with every use of a memory allocation function what function should be used to release allocated memory which is no longer needed ? Ans : free 73. : when applied to a variable, what does the unary "&" opeartor yield Ans : variable address 74. #define MAX_NUM 15 Refeferring to the sample above what is MAX_NUM ? ANS : MAX_NUM is a preprocessor macro 75. #include<stdio.h> #include<conio.h> #define max 10 void main() { int i; i = ++max; clrscr(); printf("%d",i); getch(); } Ans : C compiler error 76. #include<stdio.h> #include<conio.h> void main() { char a[5]; a[0] = 'q'; a[1] = 'u'; a[2] = 'e'; clrscr(); printf("%s",a); getch(); } Ans : garbage

77. Which one of the following provide comceptual support for function calls ? Ans : The system Stack 78. what is a difference between a decalration and a definition of a variable ? Ans : D : a declaration occur once, but a definition may occur many times 79. which one of the following C operators is right accociaative ? Ans : ^ 80. What is the purpose of realloc( )?
Ans: The function realloc(ptr,n) uses two arguments.the first argument ptr is a pointer to a block

of memory for which the size is to be altered.The second argument n specifies the<br>new size.The size may be increased or decreased.If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( ) may create a new region and all the old data are moved to the new region. 81. What is file pointer and its working method?
Ans: when a pointer is pointing to the address of a file than it is called as a file pointer.

for example: FILE *fp; here in above statement we are declaring a file pointer. there are many modes of opening a file.they are read ,write,append .. 82. Can you add pointers together?
Ans: No..pointer addition in not allowed as the address obtained by adding two pointers

83. What is an enumerator? Ans: Enumeration is a value data type, which means that enumeration contains its own values and cannot inherit or pass inheritance. Enumerator allows you to assign symbolic names or integral constants 84. What is the difference between class and structure?
Ans: 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. One more difference apart from public and private access specifier, that struct dont have protected as an access specifier while class do.

85. What is "mutable"? Answer. "mutable" is a C++ keyword. When we declare const, none of its data members can change. When we want one of its members to change, we declare it as mutable. 86. What is a dangling pointer? Ans: 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. 87. What is an adaptor class or Wrapper class? Ans: A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non-objectoriented implementation. 88. What do you mean by implicit conversion? Ans: Whenever data types are mixed in an expression then c++ performs the conversion automatically. 89. What is the invalid pointer arithmetic? Ans: i) adding ,multiplying and dividing two pointers. ii) Shifting or masking pointer. iii) Addition of float or double to pointer. iv) Assignment of a pointer of one type to a pointer of another type 90. Are the expressions *ptr ++ and ++ *ptr same? Ans: No,*ptr ++ increments pointer and not the value pointed by it. Whereas ++ *ptr increments the value being pointed to by ptr. 91. Difference between formal argument and actual argument? Ans: Formal arguments are the arguments available in the function definition. They are preceded by their own data type. Actual arguments are available in the function call. These arguments are given as constants or variables or expressions to pass the values to the function. 92. What is a huge pointer? Ans: Huge pointer is 32bit long containing segment address and offset address. Huge pointers are normalized pointers so for any given memory address there is only one possible huge address segment: offset pair. Huge pointer arithmetic is doe with calls to special subroutines so its arithmetic slower than any other pointers. 93. Explain the use of Vtable

Ans: Vtables are used for virtual functions. Its a shortform for Virtual Function Table. It's a static table created by the compiler. Compiler creates a static table per class and the data consists on pointers to the virtual function definitions. They are automatically initialised by the compiler's constructor code. 94. What is Object slicing? Give an example Ans: When a Derived Class object is assigned to Base class, the base class' contents in the derived object are copied to the base class leaving behind the derived class specific contents. This is referred as Object Slicing. That is, the base class object can access only the base class members. This also implies the separation of base class members from derived class members has happened. class base { public: int i, j; }; class derived : public base { public: int k; }; int main() { base b; derived d; b=d; return 0; } here b contains i and j where as d contains i, j& k. On assignment only i and j of the d get copied into i and j of b. k does not get copied. on the effect object d got sliced. 95. What is a data encapsulation? Ans: Data Encapsulation: The wrapping up of data and functions into a single unit (Class) is known as Encapsulation. By encapsulating the data inside the class; data is not accessible to the outside world 96. What is the difference between dynamic and static casting? Ans: static_cast are used in two cases: 1) for implicit casts that the compiler would make automatically anyway (bool to int) 2) as a mandatory forced cast (float to int).

dynamic_cast is unique to C++. It is used at runtime when info is required to make the proper cast. For eg, when you downcast a base class pointer to a derived class. 97. What is Typecasting? Explain with examples. Ans: Typecasting: C++ is very strict about type compatibility. Different variable types must be cast when their values are assigned to each other. Type cast operator is used for explicit type conversion of variables. 98. What is Mutex semaphore? Ans: Semaphore synchronizes processes where as mutex synchronizes threads running in the same process. 99. What are the syntax and semantics for a function template? Ans: Templates is one of the features of C++. Using templates, C++ provides a support for generic programming. We can define a template for a function that can help us create multiple versions for different data types 100. Guideline that should be followed while using friend function. Ans: When the application is needed to access a private member of another class, the only way is to utilize the friend functions. The following are the guidelines to handle friend functions.

Declare the function with the keyword friend that is followed by return type and followed by the function name. Specify the class whose private members are to be accessed in the friend function within parenthesis of the friend function. Write the code of the friend function in the class.

Vous aimerez peut-être aussi