Вы находитесь на странице: 1из 20

C++ virtual functions interview questions

Q1. Describe the virtual function and virtual function table. A virtual function in C++ is - A simple member function of a class which is declared with virtual keyword - It usually performs different functionality in its derived classes. - The resolving of the function call is done at run-time. Virtual Table: A virtual table is a mechanism to perform dynamic polymorphism i.e., run time binging. Virtual table is used to resolve the function calls at runtime. Every class that uses virtual functions is provided with its own virtual functions. Every entry in the virtual table is a pointer that points to the derived function that is accessible by that class. A hidden pointer is added by a compiler to the base class which in turn calls *_vptr which is automatically set when an instance of the class is created and it points to the virtual table for that class.. Q2. What is a virtual base class? An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class. C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class. Q3. What are pure virtual functions? Pure virtual functions are also called do nothing functions. e.g. virtual void abc() = 0; When a pure virtual fnction is declared in the base class, the compiler necessitates the derived classes to define those functions or redeclare them are pure virtual functions. The classes containing pure virtual functions cannot be used to declare objects of their own. Such classes are called as abstract base classes Q4. Explain the use of Vtable. 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. Since virtual function pointers are stored in each instance, the compiler is enabled to call the correct vrtual function at runtime

Q5. Explain the problem with overriding functions. Overriding of functions occurs in Inheritance. A derived class may override a base class member function. In overriding, the function names and parameter list are same in both the functions. Depending upon the caller object, proper function is invoked. Consider following sample code: class A { int a; public: A() { a = 10; } void show() { cout << a; } }; class B: public A { int b; public: B() { b = 20; } void show() { cout << b; } }; int main() { A ob1; B ob2; ob2.show(); // calls derived class show() function. o/p is 20 return 0; }

Q6.

Describe static and dynamic binding of functions.


Static Binding: By default, matching of function call with the correct function definition happens at compile time. This is called static binding or early binding or compile-time binding. Static binding is achieved using function overloading and operator

overloading. Even though there are two or more functions with same name, compiler uniquely identifies each function depending on the parameters passed to those functions. Dynamic Binding: C++ provides facility to specify that the compiler should match function calls with the correct definition at the run time; this is called dynamic binding or late binding or run-time binding. Dynamic binding is achieved using virtual functions. Base class pointer points to derived class object. And a function is declared virtual in base class, then the matching function is identified at run-time using virtual table entry.

Q7. Overloading vs. overriding



Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance. Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ. In overriding, function signatures must be same. Overridden functions are in different scopes; whereas overloaded functions are in same scope. Overriding is needed when derived class function has to do some added or different job than the base class function. Overloading is used to have same name functions which behave differently depending upon parameters passed to them

Q8. What is virtual constructors/destructors? Virtual destructors: The explicit destroying of object with the use of delete operator to a base class pointer to the object is performed by the destructor of the base-class is invoked on that object. The above process can be simplified by declaring a virtual base class destructor. All the derived class destructors are made virtual in spite of having the same name as the base class destructor. In case the object in the hierarchy is destroyed explicitly by using delete operator to the base class pointer to a derived object, the appropriate destructor will be invoked. Virtual constructor: A constructor of a class can not be virtual and if causes a syntax error Q9.. What is the object slicing? In Inheritance, the attributes of the base class get carried to the derived class. However, we can assign a base class with the derived class without having the contents of the derived that are uncommon between then, copied to the base class. Class B { public: int i; }; class D : public B { public: int j;

}; int main() { B B1; D D1; B1 = D1; //only i is copied to B1 } Q10. What is inline function? An inline function is a combination of macro & function. At the time of declaration or definition, function name is preceded by word inline. When inline functions are used, the overhead of function call is eliminated. Instead, the executable statements of the function are copied at the place of each function call. This is done by the compiler. Consider following example: #include <iostream> using namespace std; inline int sqr(int x) { int y; y = x * x; return y; } int main() { int a =3, b; b = sqr(a); cout <<b; return Q11. What is the difference between inline functions and macros? A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros: Object-like macros and function-like macros. Inline function is a function that is expanded in line when the function is called. That is the compiler replaces the function call with the function code (similar to macros). The disadvantage of using macros is that the usual error checking does not occur during compilation Q12. What are static member functions? A static function can have an access to only other static members (functions or variables) declared in the same class. A static member function can be called using the class name instead of its objects. E.g. classname :: functionname;

Q13. Do inline functions improve performance? Explain. A function when defined as INLINE, the code from the function definition is directly copied into the code of the calling function.

It avoids the overhead of calling the actual function. This is because the complier performs and inline expansion which eliminates the time overhead when a function is called. Reduces space as no separate set of instructions in memory is written.

Q14. What happens when recursion functions are declared inline? The call to the body of the function is replaced by an inline function. This reduces the saving context on stack overhead. This process is efficient when the size of the function is small and invoked occasionally. Deep nesting of a method is done when a function is invoked recursively. The inline function is invoked recursively, and every call to itself is replaced with the body of the f

Q15.Advantages and disadvantages of using macro and inline functions.


A textual substitution is provided by a macro as a constant, where as an inline function is procedure which is called at each time. Although the macros have few advantages over inline functions, the disadvantages are numerous. For example, a macro can not perform type checking and validation, as these operations are performed in a function at the most. Everyone should decide for themselves to use them, but the use of inline functions over macros is advocated by Bjarne Struoustrup, the creator of C++. The imperative features of inline functions are frequently used with classes in C++. There is similarity between invoking normal functions and inline functions, except that, inline functions are never actually called. The inline functions, as their name suggests, are expanded in line at every time of invocation. All that is needed to invoke an inline function is to prefix the key word inline to the function unction, thus consumes a lot of code space

.Q16. What is static class data? Static data members of a class are declared by preceding the member variables declaration with the keyword static. Only one copy of static data members exist and all objects of the class share that variable. Unlike regular data members, individual copies of a static member variable are not made for each object. How many ever no of objects of a class are created, only one copy of static data member is shared amongst all of them. All static variables are initialized to zero before the first object is created. When a member variable is declared static within a class, it is not defined (ie storage is not allocated for it) We must provide a global definition for it outside the class. This is done by redeclaring the static variable using scope resolution operator (::) to identify the class it belongs to. This causes storage for the class to be allocated.

Q17.Uses of static class data


1. To provide access control mechanism to some shared resource used by all the objects of a class 2. To keep track of no of objects in existence of a particular class

Q18. What are static and dynamic type checking? Type checking is the operation on which the arguments that can only be applied for. Static type checking performs the type checking operation before the execution of the program. To perform this operation, the arguments, expressions, variables must be given a data type. Dynamic type checking performs the type checking operation at the time of the program execution. To perform this operation, the arguments, expressions, variables must be given a data type. Q19. What are static variables? Static variables are the variables which has exactly one copy per class. They belong to the class as a whole but not for its instances (objects). All static variables are declared by using the modifier static. For example: Static type varidentifier; where type is the data type and varidentifier is the variable. All static variables are initialized automatically with a default value but not explicitly initialized. The default value is depended on the data type of the variables. Q20. What are volatile variables? A volatile variable is a variable which is modified asynchronously by the threads that are concurrently running in a java application. A volatile variable does not allow having a copy of variable that is local. It is a different value from the value which is currently available in main memory. A volatile variable mandatorily have its data synchronized for all the threads. So that, whenever the value of the volatile variable is updated by any thread, all other threads can access the same value immediately. Higher access and update overhead are likely to the volatile variables on contrast to plain variables, as all threads have their own set of data for efficiency considerations. Q21. What is the STL, standard template library? The Standard Template Library, or STL, is a C++ library of container classes, algorithms, and iterators; it provides many of the basic algorithms and data structures The STL includes the classes vector, list, deque, set, multiset, map, multimap, hash_set, hash_multiset, hash_map, and hash_multimap. Q22. What is the object serialization? A serialized object represents the type of data stored in the object, its information. Object serialization is a process of reading or writing an entire object from a file. This helps in saving session state information by servlets, for sending parameters for Remote Method Invocation (RMI) calls. Q23. What are ActiveX and OLE? Object Linking and Embedding (OLE) is about using documents generated by one application inside another application. ActiveX is a Microsoft rebranding of OLE with more focus on smart Windows controls.

Q24. What are GUID? Why does COM need GUIDs? Globally Unique Identifier - A 16-byte number generated by Microsoft programs that uniquely identifies a network or user or computer or document. It is one of the elements of information that can be passed when you connect to an Internet site, and it may be stored in cookies A globally unique identifier (GUID) is used for unique IDs. No two GUIDs are the same no matter what computer they were generated on. The attribute clsid defines the GUID of the associated ActiveX control to use. Q25. What is a type library? A file or component within another file that contains standard descriptions of exposed objects, properties, and methods A type library contains a binary description of an interface exposed by a COM-component. In this sense, they contain the same information that is contained in an IDL (Interface Definition Language) file Q26. What is the IUnknown interface? IUnknown interface provides clients like DirectX control of to get pointers to other interfaces. All COM interfaces are inherited from IUnknown interface. It is used In multiple inheritance where the various interfaces can share one implementation of IUnknown Q27. What is binary object model? Component Object Model COM defines an API to allow for the creation of components for use in integrating custom applications or to allow diverse components to interact. But in order to interact, components must adhere to a binary structure specified by Microsoft. As long as components adhere to this binary structure, components written in different languages can interoperate. Q28. How does COM provide language transparency? COM defines an API to allow for the creation of components for use in integrating custom applications or to allow diverse components to interact. But in order to interact, components must adhere to a binary structure specified by Microsoft. As long as components adhere to this binary structure, components written in different languages can interoperate. Q29. When should we use container classes instead of arrays? It is advisable to use container classes of the STL so that you dont have to go through the pain of writing the entire code for handling collisions, making sure its working well, testing it repeatedly with an overhead of time consumption. Suppose you have some data that has values associated with strings and its fields consist of grades> in this situation you can directly use hash table instead of having it created by yourself.

Q30. Difference between a homogeneous and a heterogeneous container A container is an object holding instances of another object. A container that contains or holds objects of a single type is said to be homogenous. On the other hand, A container that contains objects (derived from a common base class) of a variety of types is termed heterogeneous. Q31. What is a container class? What are the types of container classes? A class is said to be a container class which is utilized for the purpose of holding objects in memory or persistent media. A generic class plays a role of generic holder. A container class is a good blend of predefined behavior and an interface that is well known. The purpose of container class is to hide the topology for the purpose of objects list maintenance in memory. A container class is known as heterogeneous container, when it contains a set of different objects. A container class is known as homogeneous container when it contains a set of similar objects Q32. Describe DCOM infrastructure. Distributed Component Object Model allows applications to be distributed in a convenient way. It allows safe and reliable communication between DOM components. DCOM allows objects to be created on other machines. DCOM Class Store is used as a fixed configuration file that allow clients to indicate the remote server name when an object is created or alternatively an explicit parameter can be passed to CoCreateInstanceEx, CoGetInstanceFromFile, CoGetInstanceFromStorage, or CoGetClassObject. Q33. What is COM+? COM+ integrates MTS services and message queuing into COM, and makes COM programming easier through a closer integration with Microsoft languages as Visual Basic, Visual C++, and J++. It not only adds MTS-like quality of service into every COM+ object, but it also hides some of the complexities in COM coding Q34. Explain the problem with COM. From the security point of view, COM and ActiveX controls are not safe. As COM and ActiveX components are run as native code on the user's machine, there are fewer restrictions on what the code can do. Many of these problems have been addressed by the introduction of "code Signing" (based on digital signatures), and later by the .NET platform as well. Therefore, before an ActiveX control is installed, the user is prompted whether to allow the installation or not. It is possible to disable ActiveX controls altogether, or to only allow a selected few. Q35. Explain the problem with COM. From the security point of view, COM and ActiveX controls are not safe. As COM and ActiveX components are run as native code on the user's machine, there are fewer restrictions on what the code can do. Many of these problems have been addressed by the introduction of "code Signing" (based on digital signatures), and later by the .NET platform as well.

Therefore, before an ActiveX control is installed, the user is prompted whether to allow the installation or not. It is possible to disable ActiveX controls altogether, or to only allow a selected few. Q36. What are the different types of Inheritance?

Single Inheritance A (parent class) -> B (child class) Multiple Inheritance A -> C, B -> C Hierarchical inheritance A -> B, A -> C, A -> D Multilevel inheritance A -> B, B -> C Hybrid inheritance A -> B, A -> C, B -> D, C -> D

Q37. What is a concrete derived class? A concrete derived class has no virtual functions. It provides functions for its inherited pure virtual functions. This is to say, it provides all missing functionalities of the abstract class. Q38. Explain why and when do we use protected instead of private Private data members cannot be accessed outside the class. When a class inherits a base class, all the data members except the private get inherited into it. So if we want data members to be accessible to only derived classes and not privately or publicly accessible, then we can use protected. Q39. What is a downcast? A downcast is a cast from a base class to a class derived from the base class. A downcast is only safe if the object addressed at runtime is actually addressing a derived class object Q40. Explain Derived class with an example using C++. Inheritance is one of the important feature of OOP which allows us to make hierarchical classifications of classes. In this, we can create a general class which defines the most common features. Other more specific classes can inherit this class to define those features that are unique to them. In this case, the classes which inherit from other classes, is referred as derived class. For example, a general class vehicle can be inherited by more specific classes car and bike. The classes car and bike are derived classes in this case. class vehicle { int fuel_cap; public: drive(); }; class car : public class vehicle { public:

roll_windows(); }; class bike : public class vehicle { public: kick_start(); }; Q41. Explain how we implement exception handling in C++ Exception handling in C++ is implemented by using the try{} and catch(){} statements. When a try block throws an exception, the program leaves the try block and enters the catch statement of the catch block. If they type of the object thrown matches the arg type in the catch block, catch block is executed for handling the code. If they are not caught, abort() function is executed by default. When no exception is deteted or thrown then the control goes to the statement below the catch block. Q42. Explain terminate() and unexpected() function terminate() is a library function which by default aborts the program It is called whenever the exception handling mechanism cannot find a handler for a thrown exception. unexpected() is called when a function with an exception specification throws an exception of a type that is not listed in the exception specification for the function A function declaration without a specification like throw(char*) may throw any type of exception, and one with throw() is not allowed to throw exceptions at all. By default unexpected() calls terminate(). Q43. Exception handling concept Exceptions are certain disastrous error conditions that occur during the execution of a program. They could be errors that cause the programs to fail or certain conditions that lead to errors. If these run time errors are not handled by the program, OS handles them and program terminates abruptly, which is not good. To avoid this, C++ provides Exception Handling mechanism. The three keywords for Exception Handling are: Try, Catch and Throw. The program tries to do something. If it encounters some problem, it throws an exception to another program block which catches the exception. Ex: void main() { int no1, no2;

try { cout << Enter two nos:; cin >> no1 >> no2; if (no2 == 0) throw Divide by zero; else throw no1/no2; } catch (char *s) { cout << s; } catch (int ans) { cout << ans; } } We know that divide by zero is an exception. If user enters second no as zero, the program throws an exception, which is caught and an error message is printed else the answer is printed. Q44. Illustrate Rethrowing exceptions with an example. Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception. This causes current exception to be passed on to an outer try/catch sequence. An exception can only be rethrown from within a catch block. When an exception is rethrown, it is propagated outward to the next catch block. Consider following code: #include <iostream> using namespace std; void MyHandler() { try { throw hello; } catch (const char*) { cout <<Caught exception inside MyHandler\n; throw; //rethrow char* out of function } } int main() { cout<< Main start; try { MyHandler(); } catch(const char*) { cout <<Caught exception inside Main\n; } cout << Main end;

return 0; } Q45. What are the characteristics of friend functions? A friend function is not in the scope of the class n which it has been declared as friend. It cannot be called using the object of that class. It can be invoked like a normal function without any object. Unlike member functions, it cannot use the member names directly. It can be declared in public or private part without affecting its meaning. Usually, it has objects as arguments. Q46. What is a friend function? Private data members cannot be accessed from outside the class. However, situations arise where two classes need to share a particular function. For such situations, C++ introduces friend functions. These are functions that can be made friendly with both the classes, thus allowing these functions to have an access to the private data of these classes Q47. Explain the advantages of using friend classes. There are situations when private data members need to be accessed and used by 2 classes simultaneously. In these kind of situations we can introduce friend functions which have an access to the private data members of both the classes. Friend functions need to be declared as friend in both the classes. They need not be members of either of these classes

Q48. Guideline that should be followed while using friend function. 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.

The following code snippet illustrates the use of friend function: friend void display(car); //Friend of the class 'car' void display(car myCar) { cout<<"\nThe color of my car is : "<<myCar.color; cout<<"\nThe speed of my car is : "<<myCar.speed; } Q49. What is a base class? Inheritance is one of the important features of OOP which allows us to make hierarchical classifications of classes. In this, we can create a general class which defines the most common features. Other more specific classes can inherit

this class to define those features that are unique to them. In this case, the class from which other classes are inherited is referred as base class. For example, a general class vehicle can be inherited by more specific classes car and bike. The class vehicle is base class in this case. class Base { int a; public: Base() { a = 1; cout <<inside Base class; } }; class Derived:: public Base //class Derived is inheriting class Base publically { int b; public: Derived() { b = 1; cout <<inside Derived class; } }; Q50. What is private inheritance? When a class is being derived from another class, we can make use of access specifiers. This is essentially useful to control the access the derived class members have to the base class. When inheritance is private:

i. Private members of base class are not accessible to derived class. ii. Protected members of base class become private members of derived class. iii. Public members of base class become private members of derived class.

Q51. What is protected inheritance? When a class is being derived from another class, we can make use of access specifiers. This is essentially useful to control the access the derived class members have to the base class. When inheritance is protected:

Private members of base class are not accessible to derived class. Protected members of base class remain protected in derived class. Public members of base class become protected in derived class

Q52. How do we implement inheritance in C++? The inheritance feature in C++ is implemented in the following manner: class Square: public Shape { ... };

In the above example all public members of Shape can be reused by the class Square. If public key word is left, private inheritance takes place by default. If protected is specified the inheritance is applied for any descendant or friend class. Q53. What are ways to avoid memory leaks? A memory leak is the effect of running out of memory. A memory leak is what happens when you forget to free a block of memory allocated with the new operator or when you make it impossible to so. The measures you can take are : Delete before reallocating a memory Be sure you have a pointer to each dynamic variable so that you do not lose a location that you need to free. Avoid these combinations : malloc() - delete and new - free() Avoid these combinations : new - delete [] and new [] - delete. Q54. When are memory leaks important? What are the easiest ways to avoid memory leak? Memory Leaks: Memory leaks take up more memory space and causes slow calculation. Ensure that the loops or conditional statements are executed completely to prevent memory leak occurrence. The best and easiest way to avoid memory leaks is to make changes at the time of writing programs. The cause for this is, a properly planned program can avoid memory leaks. In addition to it, make a code snippet can be made simple, small which executes fast Q55. What is the difference between dynamic and static casting? 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 Q56. What is a namespace? What happens when two namespaces having the same name? A conceptual space for grouping identifiers, classes etc. for the purpose of avoiding conflicts with the elements of an unrelated code which have the same names. When two name spaces are having same name, the corresponding compiler uses our name spaces instead of the type.

Q57. What are the guidelines of using namespaces? To name a namespace, utilize the company name followed by the department and optionally followed by the features and technology used. For example: MyCompany.Media.Design The following are some guidelines to name namespaces.

The prefix of company name avoids the possibility of two or more namespaces with same name. Use a stable, noticeable department or technology name followed by the company name at the hierarchical name of second level. Use organizational hierarchies as the basis for name space hierarchies. Separate the logical components with periods (.). Avoid giving same name for classes and name spaces.

Q58. What is name lookup? When a function is called, which function to call is decided by the name look up. It is also known as argument dependent lookup (ADL), or argument dependent name lookup. It applies to the lookup of an unqualified function name depending on the types of the arguments given to the function call. Q59. Describe new operator and delete operator. new and delete operators are provided by C++ for runtime memory management. They are used for dynamic allocation and freeing of memory while a program is running. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new. The general form of using them is: p_var = new type; delete p_var; new allocates memory on the heap. If there is insufficient memory, then new will fail and a bad_alloc exception will be generated. The program should handle this exception.

Q60.What is dynamic memory management for array?


Using the new and delete operators, we can create arrays at runtime by dynamic memory allocation. The general form for doing this is: p_var = new array_type[size]; size specifies the no of elements in the array To free an array we use: delete[ ]p_var; // the [ ] tells delete that an array is being freed. Consider following program: #include <iostream> #include <new> using namespace std; int main() { int *p, i; try { p = new int(10); //allocate array of 10 integers } catch (bad_alloc x) { cout << Memory allocation failed; return 1; } for (i = 0; i < 10; i++) p[i] = i; for (i = 0; i < 10; i++) cout <<p[i]<<\n; delete [ ] p; //free the array return 0; } Q61. Distinguish between new and malloc and delete and free(). Delete is assocated with new and free(0 is associated with malloc() New Its an operator delete is associated with new It creates an object It throws exceptions if memory is unavailable Operator new can be overloaded You can state the number of objects to be created. malloc() Its a function free() is associated with malloc() It does not create objects It returns NULL This cannot be overloaded You need to specify the number of bytes to be allocated

Q62. What is the difference between realloc() and free()? An existing block of memory which was allocated by malloc() subroutine, will be freed by free() subroutine. In case , an invalid pointer parameter is passed, unexpected results will occur. If the parameter is a null pointer, then no action will occur. Where as the realloc() subroutine allows the developer to change the block size of the memory which was pointed to by the pointer parameter, to a specified bytes size through size parameter and a new pointer to the block is returned. The pointer parameter specified must have been created by using malloc(),calloc() or realloc() sub routines and should not deallocated with realloc() or free() subroutines. If the pointer parameter is a null pointer, then no action will occur. Q63. What is operator overloading in C++? C++ provides ability to overload most operators so that they perform special operations relative to classes. For example, a class String can overload the + operator to concatenate two strings. When an operator is overloaded, none of its original meanings are lost. Instead, the type of objects it can be applied to is expanded. By overloading the operators, we can use objects of classes in expressions in just the same way we use C++s built-in data types. Operators are overloaded by creating operator functions. An operator function defines the operations that the overloaded operator will perform on the objects of the class. An operator function is created using the keyword operator Q64. What is overloading unary operator? Unary operators are those which operate on a single variable. Overloading unary operator means extending the operators original functionality to operate upon object of the class. The declaration of a overloaded unary operator function precedes the word operator Q65. Difference between overloaded functions and overridden functions. Overloading is a static or compile-time binding and Overriding is dynamic or run-time binding. Redefining a function in a derived class is called function overriding A derived class can override a base-class member function by supplying a new version of that function with the same signature (if the signature were different, this would be function overloading rather than function overriding). Q66. What is function overloading and operator overloading? Function overloading: A feature in C++ that enables several functions of the same name can be defined with different types of parameters or different number of parameters. This feature is called function overloading. The appropriate function will be identified by the compiler by examining the number or the types of parameters / arguments in the overloaded function. Function overloading reduces the investment of different function names and used to perform similar functionality by more than one function. Operator overloading: A feature in C++ that enables the redefinition of operators. This feature operates on user defined objects. All overloaded operators provides syntactic sugar for function calls that are equivalent. Without adding to / changing the fundamental language changes, operator overloading provides a pleasant faade.

Q67. Explain the use of this pointer. The this keyword is used to represent an object that invokes the member function. It points to the object for which this function was called. It is automatically passed to a member function when it is called. e.g. when you call A.func(), this will be set to the address of A. Q68. Explain what happens when a pointer is deleted twice A pointer if not nullified and deleted twice, leads to a trap. If set to null, it wont have much affect if deleted twice. Q69. What is a smart pointer? Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They are like built-in C++ pointers. However, they automatically delete the object pointed to at the appropriate time. They are useful as they ensure proper destruction of dynamically allocated objects (Exceptions). They can also be used to keep track of dynamically allocated objects shared by multiple owners. They appear as owning the object pointed to and are responsible for deletion of the object when it is no longer needed. The smart pointer library provides five smart pointer class templates: scoped_ptr : Simple sole ownership of single objects. Noncopyable. scoped_array: Simple sole ownership of arrays. Noncopyable. shared_ptr: Object ownership shared among multiple pointers shared_array: Array ownership shared among multiple pointers. weak_ptr: Non-owning observers of an object owned by shared_ptr. intrusive_ptr: Shared ownership of objects with an embedded reference count. These templates are designed to complement the std::auto_ptr template Q70. What is the difference between an inspector and a mutator? An objects state is returned without modifying the objects abstract state by using a function called inspector. Invoking an inspector does not cause any noticeable change in the objects behavior of any of the functions of that object. A mutator, on the other hand, changes the state of an object which is noticeable by outsiders. It means, it changes the abstract state of the object. The following code snippet depicts the usage of these two functions: class ShoppingCart { public: int addItem(); //Mutator int numItems() const; //Inspector }; The function addItems() is a mutator. The reason is that it changes the ShoppingCart by adding an item. The function numItems() is an inspector. The reason is that it just updates the count of number of items in the ShoppingCart. The const declaration followed by int numItems() specifies that numItems() never change the ShoppingCart object

Q71. What is pointer? Explain with examples A pointer is a variable that holds a memory address. This address is the location of another object (typically, a variable) in memory. That is, if one variable contains the address of another variable, the first variable is said to point to the second. A pointer declaration consists of a base type, an *, and the variable name. The general form of declaring a pointer variable is: type *name; type is the base type of the pointer and may be any valid type. name is the name of pointer variable. The base type of the pointer defines what type of variables the pointer can point to.

Two special pointer operators are: * and &. The & is unary operator that returns the memory address of its operand. It is the address of operand. The * is complement of &. It is also a unary operator and returns the value located at the address that follows. int i, *p; i = 5; p = &i;

//places the memory address of i into p

The expression *p will return the value of variable pointed to by p Q72. Pointer to constant vs. pointer constant Pointer to constant points to a value that does not change and is declared as: const type * name type is data type name is name of the pointer e.g: const char *p; pointer to constant can not be used to change the value being pointed to. Therefore: char ch = A; const char *p = &ch; *p = B; is not allowed. The program will throw an error. Pointer Constant (or constant pointer) is a pointer which you dont want to be pointed to a different value. That is, the location stored in the pointer can not change. We can not change where the pointer points. It is declared as: type * const name type is data type name is name of the pointer eg: char * const p Since the location to which a const pointer points to can not be changed, the following code: char ch1 = A; char ch2 = B;

char * const p = &ch1; p = &ch2; will throw an error since address stored in p can not be changed

Вам также может понравиться