Faq In C++

  • December 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Faq In C++ as PDF for free.

More details

  • Words: 6,673
  • Pages: 20
FAQ in C++ by

SOLVED WORLD

0

PRESENTS… PRESENTS…

THIS PDF ANSWERS ALL THE C++ INTERVIEW QUESTIONS AVAILABLE IN SOME RENOWNED WEBSITES LIKE www.jobs_junction.com AND ANYTHING WRITTEN OR DRAWN IN THE PDF IS AN EFFORT OF SOLVED WORLD GROUP.

01.01.2009

P.T.O.

FAQ in C++ by

SOLVED WORLD

1

WHAT IS SOLVED WORLD SOLVED WORLD is a group of engineering & technical students which produces number of solutions of question papers available in various job sites and number of study materials on different subjects in the .pdf or .ppt format. Anything written or drawn under the SOLVED WORLD logo is the effort of this group. We believe in helping. If you have any query or if you need any solutions or study materials you can mail us at [email protected] (depends on availability).

P.T.O.

FAQ in C++ by

SOLVED WORLD

2

1. What is a class? A class is a way to bind data and associated functions together. Actually, class is an extension of the data type structure which can hold data and functions both as its members with providing data hiding property. Class is a new kind of data type. A class is usually declared as follows:class A { int number; float cost; public : void get_data(int a, float b); void put_data( void); };

Generally, variables are declared as private by default and functions are made public. 2. What is an object? Class variables are called objects. There are two types of procedures to create objects. Most common procedure is to create them at the place of their use. Creation of object at the place of their use

Creation of object at the start of the program

class A { int number; float cost; public : void get_data(int a, float b); void put_data(void); }; - - - - - - - - - - - - - - - - item x,y; - - - - - - - - - - - - - - - - -

class A { int number; float cost; public : void get_data(int a, float b); void put_data(void); }x,y; -

- - - - - - - - - - - - - - -

Here, x & y are the two objects created of the class item. By the creation of objects, the necessary memory space is allocated. The purest definition of object may be “a region of storage” (this is a more specific way of saying, “an object must have a unique identifier,” which in the case of C++ is a unique memory address). It’s a place where we can store data, and it’s implied that there are also operations that can be performed on this data. 3. What is the difference between an object and a class? Class is a special type of data types (much like structure with some additional features) but objects are the variables of a class. 4. What is the difference between class and structure? The members of a structure are public by default, while in class, the members are private by default. In a class, one can make a member public or private or protected as per his/her desire. But, structure does not provide data hiding.

P.T.O.

FAQ in C++ by

SOLVED WORLD

3

5. What is public, protected, private? Public, protected & private are the three access specifiers used to select the nature of the class members.  A member (data or function) declared in a public section of a class can be accessed by anyone.  A member (data or function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes.  A member (data or function) declared in a private section of a class can only be accessed by member functions and friends of that class. 6. What are virtual functions? A virtual function allows derived classes to replace the implementation provided by the base class. When we use the same function name (or we want to enjoy runtime-polymorphism) in the base and the derived class, the function in the base class is declared virtual as shown below: class base { - - - - - - Public: virtual void show() { - - body of the show function - - } }; class derived : public base { - - - - - - void show() { - - body of the show function - - } }; Once the “show()” function is made virtual, we can execute different versions (base version or derived version) of the “show()” function by pointing the base

pointer to different objects. For example: main() { base b; derived d; base *bptr; bptr = &b; bptr -> show(); //calls base version bptr = &d; bptr -> show(); //calls derived version - - - - - - } But, if the “show()” function was not declared virtual, the base pointer (even

when it was made to contain the address of the derived class) would always calls the base version and always the base version would be executed. That is we would fail to achieve run time polymorphism. This problem is solved by using virtual functions. 7. What is friend function? Friend functions are non member functions of a class who can access the private members of that class. It is a non member function, but it must be listed in the class definition. class A { - - - - - - -

P.T.O.

FAQ in C++ by

SOLVED WORLD - - - - - public : - - - - - - - - - - friend void - - - - - - - - - - };

4

- - - XYZ(void); - - -

The friend function XYZ may be defined any where in the program later. But this type of definition differs from usual member function definition. The difference is that there is no need for the scope resolution operator. The definition is like that: void XYZ(void);

Also, the definition does not need the keyword friend again. 8. What is a scope resolution operator? A scope resolution operator :: is used to define the member functions of a class outside the class. The declaration and definition of the function is as follows: class A { int number; float cost; public : void get_data(int a, float b); void put_data(void); }; void item :: get_data(int a, float b) { number = a; cost = b; }

//declaration //definition

9. What do you mean by inheritance? The C++ classes can be reused in several ways. Once, a class is written and tested it can be adopted by other programmers. This is basically done by creating a new class reusing the properties of the existing classes. Inheritance is the process of creating new classes (derived classes) from existing classes (base classes). The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own. 10. What is abstraction? Abstraction is of the process of hiding unwanted details from the user. The concept of abstraction relates to the idea of hiding data that are not needed for presentation. 11. What is polymorphism? Explain with an example.

P.T.O.

FAQ in C++ by

SOLVED WORLD

5

“Poly” means “many” and “morph” means “form”. Polymorphism is the ability of an object to behave differently. This is a crucial feature of OO languages that provides a mean to extend the functionality of an object. The types of polymorphism are shown in figure. Compile time polymorphism is implemented by overloaded functions & operators. The overloaded member functions are selected for invoking by matching arguments (both type & number). This information is known to the compiler at the compile time and so the compiler is able to select the particular function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism, the early binding simply means that the object is bound to its function call at the compile time. For example, the function “add( )” can be overloaded as follows:

Again, an example of operator overloading can be the addition ‘+’ operator is used for adding two integers or to concatenate two strings. 12. What is encapsulation? It is n way of preventing unauthorized access to some piece of information or functionality. The key money-saving insight is to separate the volatile part of some chunk of software from the stable part. Encapsulation puts a firewall around the chunk, which prevents other chunks from accessing the volatile parts; other chunks can only access the stable parts. This prevents the other chunks from breaking if the volatile parts are changed. In context of OO software, a “chunk” is normally a class or a tight group of classes. The “volatile parts” are the implementation details. If the chunk is a single class, the volatile part is normally encapsulated using the private and/or protected keywords. If the chunk is a tight group of classes, encapsulation can be used to deny access to entire classes in that group. Inheritance can also be used as a form of encapsulation. The “stable parts” are the interfaces. A good interface provides a simplified view in the vocabulary of a user, and is designed from the outside-in (here a “user” means another developer, not the end-user who buys the complete application). If the chunk is a single class, the interface is simply the class's public member functions and friend functions. If the chunk is a tight group of classes, the interface can include several of the classes in the chunk. Designing a clean interface and separating that interface from its implementation merely allows users to use the interface. But encapsulating (putting “in a capsule”) the implementation forces users to use the interface.

P.T.O.

FAQ in C++ by

SOLVED WORLD

6

13. What do you mean by binding of data and functions? This is encapsulation. In other words, it is the ability to package data with functions which allows us to create a new data type, called “class”. 14. What is function overloading and operator overloading? Function overloading: - Function overloading is one type of compile-timepolymorphism. Here, we use different functions of the same name in different tasks. For example, the function “add( )” can be overloaded as follows:

Operator overloading: - Operator overloading is one of the exciting features of C++ which gives the ability to provide operators with a special meaning for a data type. We can overload all C++ operators except:  Class member access operator ( “.”, “,” and “.*”).  Scope resolution operator ( “::”).  Size operator ( “sizeof”).  Conditional operator ( “?” and “:”). Operator overloading provides a flexible option for the creation of new definitions of some C++ operators. The additional task can be given to the operator by using operator function as follows: :: (op_areglist) { - - - function body - - - } // task defined

We can almost create a new language of our own by creative use of operator overloading and function overloading together. Following are the examples of operator overloading. The following code shows some operators (in pink) being applied to objects of type “Intlist”:IntList L1, L2, L3; L1 += 10; L3 = L1 + L2; cout << L1; if (L1[0] == 5)- - if (L1 == L2)- - -

It is important to note that if we do not define these operators to apply to our class, we will get a compile-time error if when we write code that does apply them to class objects; the compiler supplies a default version only for operator “=” (assignment). Note also that when we overload operators, at least one operand must be a class object (or an enum). For example, you we redefine the plus operator applied to an “IntList” and an integer, or to two “IntLists”, but we cannot redefine plus applied to two integers. We also cannot redefine the parity of an operator; for example, we cannot define plus to have three operands. Unary operators, and binary operators whose left operands are class objects, can be

P.T.O.

FAQ in C++ by

SOLVED WORLD

7

defined either as member functions of that class, or as free functions. Binary operators whose left operands are not class objects must be defined as free functions. Now, we will verload the operator “+=”. In the statement: L1 += 10;

the left operand of += is an “IntList”, and its right operand is an integer. Therefore, this version of += can be defined either as an “IntList” member function or as a free function. Here is how it might be defined as a member function: class IntList { public: void operator+=( int n ); - - - }; void IntList::operator+=( int n ) { AddToEnd( n ); }

Note that it is up to the designer of the class to decide what it means to apply an operator to a class object. This definition of operator+= adds the right-hand operand (the integer value) to the end of the list represented by the left-hand operand (the “IntList” whose member function is called). It would also be reasonable to define operator+= to add the integer to the front of the list. 15. What is virtual class and friend class? Virtual class: - This is also known as virtual base class.

Consider a case where all types of inheritances occur namely, multiple, multilevel and hierarchical. The “Child” class inherits both the “Parent” classes, “Parent 1 & 2”. The two “Parents” are having a common base class “Grandparent”. The “Child” can inherit the traits of “Grandparent” via the two “Parents” or directly (dotted line) form the “Grandparent”. Now, during inheritance via “Parents”, the “Child” may have duplicate sets of members from “Grandparent”, as all public and protected members are inherited twice from the “Parents” by the “Child”. To avoid this we need to make the “Grandparent” virtual as follows: class class class class

Grandparent {- - -}; Parent1 : virtual public Grandparent {- - -}; Parent2 : virtual public Grandparent {- - -}; Child : public Parent1, public Parent2 {- - -};

So, this is the concept behind virtual classes or virtual base classes.

P.T.O.

FAQ in C++ by

SOLVED WORLD

8

Friend class:- In object-oriented programming to allow access to “private” or “protected” data of a class in another class, the latter class is declared as a friend class. A friend class has full access to the private data members of a class without being a member of that class. A friend class can be declared as shown: class A { - - - - - - - - public: - - - - - - - - friend class B; }

In this example class B has access to private and protected data and member functions of class A. 16. What do you mean by inline function? The idea behind inline functions is to insert the code of a called function at the point where the function is called. Any function defined within a class body is automatically inline, but we can also make a non-class function inline by preceding it with the inline keyword. The syntax is: inline int plusOne(int x) { return ++x; }

We almost always want to put inline definitions in a header file. When the compiler sees such a definition, it puts the function type (the signature combined with the return value) and the function body in its symbol table. When we use the function, the compiler checks to ensure the call is correct and the return value is being used correctly, and then substitutes the function body for the function call, thus eliminating the overhead. The inline code does occupy space, but if the function is small, this can actually take less space than the code generated to do an ordinary function call. 17. What do you mean by public, private, protected and friendly? Public, protected & private are the three access specifiers used to select the nature of the class members.  A member (data or function) declared in a public section of a class can be accessed by anyone.  A member (data or function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes.  A member (data or function) declared in a private section of a class can only be accessed by member functions and friends of that class.  There is no keyword like friendly. A class may be friendly to another class (see friend class in question number 15) or a function may be friendly to a class (see friend function in question number 7). 18. When an object created and what is is its lifetime? Objects can be created whenever it is required by the programmer. The life-cycle for an object begins when it is created, and ends when it is destroyed. Whenever object of the class is created, constructor is called automatically. Constructors are

P.T.O.

FAQ in C++ by

SOLVED WORLD

9

typically used to initialize the data members of the object to their default state, but may also be used to allocate memory. When the object is deleted, a destructor is called automatically. The destructor is typically used to deallocate the memory allocated for that object. 19. What do you mean by multiple inheritance and multilevel inheritance? Differentiate between them. Multiple inheritance: - In this type of inheritance, the derived class can inherits the attributes of two or more classes. For example, a tall & fair child (C) inherits the tallness of the father (F) and the fairness of the mother (M). This is shown in the figure below. Here, F & M are the two base classes and C is the derived class.

The syntax of derived class with multiple base classes is as follows:class F { - - Body of first base class F - - }; class M { - - Body of second base class M - -}; class C : public F, public M {- - Body of derived class C - - -};

The access specifier may be public, protected or private Multilevel inheritance: - This is the process of deriving one class from another derived class which was derived from a base class.

In the above figure, B1 is the base claas from where the class D1 is derived and D2 is again derived from D1. The syntax of multilevel inheritance is given below: class B1 { - - Body of base class B1 - - }; class D1 : public B1 { - - Body of derived class D1 - - }; class D2 : public D1 { - - Body of derived class D2 - - };

20. Difference between realloc() and free? realloc()

free()

P.T.O.

FAQ in C++ by i.

SOLVED WORLD

The syntax is:

10 i.

void * realloc ( void * ptr, size_t size );

ii.

iii.

iv.

It reallocates memory block. The size of the memory block pointed to by the ptr parameter is changed to the size bytes, expanding or reducing the amount of memory available in the block. It has two parameters. 1) ptr:- Pointer to a memory block previously allocated with malloc(), calloc() or realloc() to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function. 2) size:- New size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned. It returns a pointer to the reallocated memory block, which may be either the same as the ptr argument or a new location. The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a NULL pointer is returned.

The syntax is: void free ( void * ptr );

ii.

iii.

It deallocates space in memory. A block of memory previously allocated using a call to malloc(), calloc() or realloc() is deallocated, making it available again for further allocations It has a single parameter ptr. It is a pointer to a memory block previously allocated with malloc(), calloc() or realloc() to be deallocated. If a null pointer is passed as argument, no action occurs.

iv.

It returns nothing.

21. What is a template? Template is a new concept in c++ that helps to implement generic programming where generic types are used as parameters in algorithms so that they can work for variety of datatypes and data structures. There are two applications of templates: “class templates” and “function templates”. But, only the word “template” generally refers to class template which is discussed in question number 24.

P.T.O.

FAQ in C++ by

SOLVED WORLD

11

22. What are the main differences between procedure oriented languages and object oriented languages? Procedure oriented languages i.

ii.

iii.

iv.

v.

Object oriented languages

In procedure oriented i. languages, importance is given to the sequence of things to be done. In procedure oriented ii. languages, larger programs are divided into functions. In procedure oriented iii. languages, most functions share global data. Procedure oriented languages follows a top down approach in problem solving. For example PASCAL, C etc.

iv.

v.

In object oriented languages, importance is given to the data. In object oriented languages, larger programs are divided into objects. In object oriented languages, mostly the data is private and only functions inside the object can access the data. Object oriented languages follow a bottom up approach. For example, SMALLTALK, JAVA, C#, C++ etc.

23. What is R T T I? Run Time Type Identification is a mechanism that helps us to determine the type of an object during program execution. There are three main C++ language elements for RTTI as follows: The dynamic_cast operator: Used for conversion of polymorphic types. The typeid operator: Used for identifying the exact type of an object. The typeinfo class: Used to hold the type information returned by the typeid operator. 24. What are generic functions and generic classes? Generic functions: - Generic functions are functions that can be used for operations on several data types at time. The concept of template enables us to define generic functions. For example, consider a swapping program using templates as follows: template void swap(T &x, T &y); { temp = x; x = y; y = temp; } We can invoke the swap() like an ordinary function as follows: void f(int m, int n, float a, float b) { swap(m,n) //swap two integers swap(a,b) //swap two floats }

P.T.O.

FAQ in C++ by

SOLVED WORLD

12

Here, the function swap() is generic because it is used for swapping integers and floats at a time. Generic class:- Generic classes are those classes that can have members that use template parameters as types. For example: template class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } }; The class mypair is used to store two elements of any datatype. For example, if

we wanted to declare an object of this class to store two integers 15 & 14 we’ll write: mypair myobject (115, 36);

the same class can also be used to create an object to store floats: mypair<double> myfloats (3.0, 2.18);

25. What is namespace? Namespaces allow us to group a set of global classes, objects and/or functions under a name. They serve to split the global scope in sub scopes known as namespaces. The form to use namespaces is: namespace { namespace-body } Where identifier is any valid identifier and namespace-body is the set of

classes, objects and functions that are included within the namespace. For example: namespace admiral { int a, b; }

In this case, a and b are normal variables integrated within the admiral namespace. In order to access to these variables from outside the namespace we have to use the scope resolution operator ::. For example, to access the previous variables we would have to put: admiral::a admiral::b

The functionality of namespaces is especially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error. 26. What is the difference between pass by reference and pass by value? Pass by value:- When we pass an argument to a function, a copy of that argument is made inside the function. This is referred to as pass-by-value. The effect of pass-by-value is shown bellow: void f(int a) { cout << "a = " a = 5; cout << "a = " } int main() { int x = 47; cout << "x = " f(x); cout << "x = "

<< a << endl; << a << endl;

<< x << endl; << x << endl;

P.T.O.

FAQ in C++ by

SOLVED WORLD

13

}

In f( ), a is a local variable, so it exists only for the duration of the function call to f( ). Because it’s a function argument, the value of a is initialized by the arguments that are passed when the function is called; in main( ) the argument is x, which has a value of 47, so this value is copied into a when f( ) is called. When we run this program we’ll see: x = 47 a = 47 a = 5 x = 47 Initially, of course, x is 47. When f( ) is called, temporary space is created to hold the variable a for the duration of the function call, and a is initialized by copying the value of x, which is verified by printing it out. Of course, we can change the value of a and show that it is changed. But when f( ) is completed, the temporary space that was created for a disappears, and we see that the only connection that ever existed between a and x happened when the value of x was copied into a. Pass by reference:- C++ allows an additional way to pass an address into a function. This is pass-by-reference. void f(int& r) { cout << "r = " << r << endl; cout << "&r = " << &r << endl; r = 5; cout << "r = " << r << endl; } int main() { int x = 47; cout << "x = " << x << endl; cout << "&x = " << &x << endl; f(x); // Looks like pass-by-value, // is actually pass by reference cout << "x = " << x << endl; }

In f( )’s argument list, we make int& to pass a reference. Inside f( ), if we just say ‘r’ (which would produce the address if r were a pointer) we get the value in the variable that r references. If we assign to r, we actually assign to the variable that r references. In fact, the only way to get the address that’s held inside r is with the ‘&’ operator. In main( ), we can see the key effect of references in the syntax of the call to f( ), which is just f(x). Even though this looks like an ordinary pass-by-value, the effect of the reference is that it actually takes the address and passes it in, rather than making a copy of the value. The output is: x = 47 &x = 0065FE00 r = 47 &r = 0065FE00 r = 5 x = 5

P.T.O.

FAQ in C++ by

SOLVED WORLD

14

So you can see that pass-by-reference allows a function to modify the outside object, just like passing a pointer does in C. Actually in C, pointer passing is the only way to pass-by-reference as it does not support a reference to be passed directly. You can also observe that the reference obscures the fact that an address is being passed. 27. Why do we use virtual functions? We use it to achieve dynamic polymorphism. For a virtual function which is defined in both the base and derived classes, the decision of which implementation to call is taken at runtime depending on the type of object, and NOT depending on the declaration type of pointer/reference. For example: When we use the same function name in the base and the derived class, the function in the base class is declared virtual as shown below: class base { - - - - - - Public: virtual void show() { - - body of the show function - - } }; class derived : public base { - - - - - - void show() { - - body of the show function - - } }; Once the “show()” function is made virtual, we can execute different versions (base version or derived version) of the “show()” function by pointing the base

pointer to different objects. For example: main() { base b; derived d; base *bptr; bptr = &b; bptr -> show(); //calls base version bptr = &d; bptr -> show(); //calls derived version - - - - - - } But, if the “show()” function was not declared virtual, the base pointer (even

when it was made to contain the address of the derived class) would always calls the base version and always the base version would be executed. That is we would fail to achieve run time polymorphism. This problem is solved by using virtual functions. 28. What do you mean by pure virtual functions? A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. They exist in concept; they don't have any reasonable definition. Pure virtual functions are equated to zero. class Shape { public: virtual void draw() = 0; };

P.T.O.

FAQ in C++ by

SOLVED WORLD

15

29. What are virtual classes? This is also known as virtual base class.

Consider a case where all types of inheritances occur namely, multiple, multilevel and hierarchical. The “Child” class inherits both the “Parent” classes, “Parent 1 & 2”. The two “Parents” are having a common base class “Grandparent”. The “Child” can inherit the traits of “Grandparent” via the two “Parents” or directly (dotted line) form the “Grandparent”. Now, during inheritance via “Parents”, the “Child” may have duplicate sets of members from “Grandparent”, as all public and protected members are inherited twice from the “Parents” by the “Child”. To avoid this we need to make the “Grandparent” virtual as follows: class class class class

Grandparent {- - -}; Parent1 : virtual public Grandparent {- - -}; Parent2 : virtual public Grandparent {- - -}; Child : public Parent1, public Parent2 {- - -};

So, this is the concept behind virtual classes or virtual base classes. 30. Does c++ support multilevel and multiple inheritances? Yes. C++ supports multiple & multilevel inheritance. 31. What are the advantages of inheritance?  Inheritance (& composition also) provide a way to reuse object code. This code reusability results in rapid project development by saving time.  It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional. 32. When is a memory allocated to a class? When the class variables (objects of the class) are declared, the memory space is allocated. 33. What is the difference between declaration and definition? A declaration introduces a name (an identifier) to the compiler. It tells the compiler “This function or this variable exists somewhere, and here is what it should look like”. A definition, on the other hand, says: “Make this variable here” or “Make this function here.” It allocates storage for the name. This meaning works for either a variable or a function. In either case, at the point of definition the compiler allocates storage. For a variable, the compiler determines how big P.T.O.

FAQ in C++ by

SOLVED WORLD

16

that variable is and causes space to be generated in memory to hold the data for that variable. For a function, the compiler generates code, which ends up occupying storage in memory. A function declaration and definition is shown below: class A { int number; float cost; public : void get_data(int a, float b); void put_data(void); }; void item :: get_data(int a, float b) { number = a; cost = b; }

//declaration //definition

34. What are virtual constructors/destructors? C++ does not allow virtual constructor. According to OOP basics, the derived class object can be created after the creation of base class object. Now, virtual constructor creates object of derived class. When pointer points to derived type object it fetches derived constructor directly, without its base class object constructed. This is not supported in C++. So there is no virtual constructor in C++. But, virtual destructors are allowed in C++. Virtual destructors are used to call the destructor of the correct object. For example: class Base1 { public: ~Base1() { cout << "~Base1()\n"; } }; class Derived1 : public Base1 { public: ~Derived1() { cout << "~Derived1()\n"; } }; class Base2 { public: virtual ~Base2() { cout << "~Base2()\n"; } }; class Derived2 : public Base2 { public: ~Derived2() { cout << "~Derived2()\n"; } }; int main() { Base1* b1p = new Derived1; delete b1p; // calls base class destructor Base2* b2p = new Derived2; delete b2p; // calls derived class destructor }

When we run the program, we see that delete b1p only calls the base-class destructor, while delete b2p calls the derived-class destructor followed by the base-class destructor, which is the behavior C++ allows. 35. In c++ there are only virtual destructors, no constructors. Why? According to OOP basics, the derived class object can be created after the creation of base class object. Now, virtual constructor creates object of derived class. When pointer points to derived type object it fetches derived constructor

P.T.O.

FAQ in C++ by

SOLVED WORLD

17

directly, without its base class object constructed. This is not supported in C++. So there is no virtual constructor in C++. 36. What is late bound function call and early bound function call? Differentiate. The procedure of connecting a function call to the function body is called binding. When binding is performed before the program is run (by the compiler and linker), it’s called early binding. C compilers have only early binding. The problem by early binding is that the compiler cannot know the correct function to call. Here late binding is the solution, where binding occurs at runtime, based on the type of the object. When a language implements late binding, there must be some mechanism to determine the type of the object at runtime and call the appropriate member function. In the case of a compiled language, the compiler still doesn’t know the actual object type, but it inserts code that finds out and calls the correct function body. The late-binding mechanism varies from language to language. For example, in C++, mechanism of virtual table or VTABLE is used. 37. How is exception handling carried out in c++? There are some extra problems, encountered by the program when it is being executed, except the logic error or syntax error. They are known as exceptions. They may be some conditions like “divide by zero”, “access to an array outside its bounds”, “running out of memory/disc space” etc. basically exceptions are of two types:– synchronous (out-of-range-index, overflow) and asynchronous (keyboard interrupt – errors beyond the control of the program). ANSI C++ provides builtin-language to detect and to handle the exceptions. The exception handling mechanism suggests a separate error handling code that performs the following tasks:  Find the problem (hit the exception).  Inform that an error has occurred (throw the exception).  Receive the error information (catch the exception).  Take corrective actions (handle the exception).

C++ exception handling is basically built upon three keywords, namely try, throw & catch. The keyword try is used to preface a block of statements (surrounded by braces) which may generate exceptions. The block of statements is known as “try block”. When an exception is detected, it is thrown using a throw statement in the “try block”. A “catch block”, defined by the keyword

P.T.O.

FAQ in C++ by

SOLVED WORLD

18

catch, catches the exception thrown in the try block and handles it appropriately.

The relationship is shown in figure. 38. When will a constructor executed? The constructor will be executed or automatically invoked when the objects of the corresponding class will be created. For example: class integer { int m,n public : integer() {m = 0; n = 0;} }; - - - - - - - - - - - - integer I ; - - - - - - - - - - - - -

In the above program, we declared & defined a constructor inside the class. Now, the statement “integer I ;” will creates an integer object I1 and then & their the constructor will be invoked and set m & n to “0”. In this way constructor is executed. 39. What is Dynamic Polymorphism? When we can call and execute our desired function from a group of different functions having the same name which belong to base or derived classes when the program is running, dynamic polymorphism or run-time- polymorphism or dynamic binding is said to be achieved. When we use the same function name in the base and the derived class, the function in the base class is declared virtual as shown below: class base { - - - - - - Public: virtual void show() { - - body of the show function - - } }; class derived : public base { - - - - - - void show() { - - body of the show function - - } }; Once the “show()” function is made virtual, we can execute different versions (base version or derived version) of the “show()” function by pointing the base

pointer to different objects. For example: main() { base b; derived d; base *bptr; bptr = &b; bptr -> show(); //calls base version bptr = &d; bptr -> show(); //calls derived version - - - - - - } But, if the “show()” function was not declared virtual, the base pointer (even

when it was made to contain the address of the derived class) would always calls the base version and always the base version would be executed. That is we

P.T.O.

FAQ in C++ by

SOLVED WORLD

19

would fail to achieve run time polymorphism. This problem is solved by using virtual functions. 40. What is friend function? Friend functions are non member functions of a class who can access the private members of that class. It is a non member function, but it must be listed in the class definition. class A { - - - - - - - - - public : - - - - - - - - - - friend void - - - - - - - - - - };

- - - - XYZ(void); - - -

The friend function XYZ may be defined any where in the program later. But this type of definition differs from usual member function definition. The difference is that there is no need for the scope resolution operator. The definition is like that: void XYZ(void);

Also, the definition does not need the keyword friend again. 41. Write a macro for swapping integers. #define SWAP(i,j) ((i==j)||((i)^=(j)),((j)^=(i)),((i)^=(j)))

The XOR technique is used. This technique is free from overflow and round off errors that are common in swapping program. The first OR condition (i==j) is checked before the actual SWAP. Otherwise, it would fail to work when we try to swap the same memory location.

E-mail us at [email protected]

P.T.O.

Related Documents

Faq In C
November 2019 13
Faq In C++
December 2019 8
C++ Faq
November 2019 11
Faq-c
November 2019 8
C#faq
November 2019 4
C++faq
November 2019 5