Sunteți pe pagina 1din 12

1. What is the only function all C++ programs must contain? main() 2.

What punctuation is used to signal the beginning and end of code blocks? {} 3. What punctuation ends most lines of C++ code? ; 4. What is the symbol for boolean operator for logical-and? && 5. Evaluate !(1 && !(0 || 1)). True 6. The void specifier is used if a function does not have return type.(t/f) true 7. You must specify void in parameters if a function does not have any arguments. .(t/f) false 8. Type specifier is optional when declaring a function. No 9. What is C++? Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory management and adding several features - including a new datatype known as a class (you will learn more about these later) - to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management. C++ used for: C++ is a powerful general-purpose programming language. It can be used to create small programs or large applications. It can be used to make CGI scripts or console-only DOS programs. C++ allows you to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++. 10. What is function overloading ? Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. 11. What is operator overloading? Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs). 12. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition of this declaration. E.g.: void stars () //function declaration The definition contains the actual implementation. E.g.: void stars () // declarator { for(int j=10; j > =0; j--) //function body cout << *; cout << endl; }

13. What are the advantages of inheritance? It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional. 14. 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. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables. 15. Write a short code using C++ to print out all odd number from 1 to 100 using a for loop #include <iostream> using namespace std; int main() { int i=99; while(i>0) { cout << i << endl; i = i - 2; } return 0; } 16. Does c++ support multilevel and multiple inheritance? Yes. 17. What is a template? Templates allow to create generic functions that admit any data type as parameters and return 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 <class indetifier> function_declaration; template <typename indetifier> function_declaration; The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way. 18. Define a constructor - What it is and how it might be called. constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized. Ways of calling constructor: 1) Implicitly: automatically by complier when an object is created. 2) Calling the constructors explicitly is possible, but it makes the code unverifiable. 19. What is the difference between class and structure? 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.

20. Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects POLYMORPHISM : A phenomenon which enables an object to react differently to the same function call. in C++ it is attained by using a keyword virtual Example public class SHAPE { public virtual void SHAPE::DRAW()=0; } Note here the function DRAW() is pure virtual which means the sub classes must implement the DRAW() method and SHAPE cannot be instatiated public class CIRCLE::public SHAPE { public void CIRCLE::DRAW() { // TODO drawing circle } } public class SQUARE::public SHAPE { public void SQUARE::DRAW() { // TODO drawing square } } now from the user class the calls would be like globally SHAPE *newShape; When user action is to draw public void MENU::OnClickDrawCircle(){ newShape = new CIRCLE(); } public void MENU::OnClickDrawCircle(){ newShape = new SQUARE(); } the when user actually draws public void CANVAS::OnMouseOperations(){ newShape->DRAW(); } 21. What is an object? Object is a software bundle of variables and related methods. Objects have state and behavior. 22. Describe PRIVATE, PROTECTED and PUBLIC the differences and give examples. public, protected, private are access specifiers that is used to implement encapsulation of data at various level.

Private: * Can be data or method members * Are private to the class where they are declared * Accessible ONLY by the member methods of the class where they are declared * Only exception to the above rule is Friend (explanation of friends is beyond the scope of this topic * In a C++ class, private is default for member declaration. That is, if you do not specify any access specifier (private, public, protected), the member is considered private Public: * Can be data or method members * Are accessible by any function/method/application globally, so long as an instance of the class where the public members are declared is created. * These members are accessible only thru an instance of the class where they are declared * Generally used to define a C++ class behaviour and/or to access private data members (act as private data modifiers) Protected * Can be data or method members * Act exactly as private members for all practical purposes, so long as they are referenced from within the class (and/or instances of the class)where they are declared * Specifically used to define how certain data/method members of a class would behave in a child class (used to define their behaviour in inheritance) * The protected members become private of a child class in case of private inheritance, public in case of public inheritance, and stay protected in case of protected inheritance. 23. What is namespace? 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. The form to use namespaces is: namespace identifier { 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 general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put: general::a general::b The functionality of namespaces is specially 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. 24. What is a COPY CONSTRUCTOR and when is it called? A copy constructor is a method that accepts an object of the same class and copies its data members to the object on the left part of assignement: class Point2D{ int x; int y; public int color; protected bool pinned; public Point2D() : x(0) , y(0) {} //default (no argument) constructor public Point2D( const Point2D & ) ;

}; Point2D::Point2D( const Point2D & p ) { this->x = p.x; this->y = p.y; this->color = p.color; this->pinned = p.pinned; } main(){ Point2D MyPoint; MyPoint.color = 345; Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345 25. What is virtual class Virtual Base Class: Used in context of multiple inheritance in C++. If you plan to derive two classes from a class, and further derive one class from the two classes in the second level, you need to declare the uppermost base class as 'virtual' in the inherited classes. This prevents multiple copies of the uppermost base class data members when an object of the class at the third level of hierarchy is created. 26. What is friend class? 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. 27. What is the word you will use when defining a function in base class to allow this function to be a polymorphic function? virtual 28. What do you mean by binding of data and functions? Encapsulation 29. What is friend function? As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition. 30. What are virtual functions? A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class. 31. What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator. An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object. An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through while an internal iterator is implemented with member functions of the class that has items to step through. With an external iterator many different iterators can be active simultaneously on the same object - this is its basic advantage.

32. What is a scope resolution operator? A scope resolution operator (::), can be used to define the member functions of a class outside the class. 33. 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. Pure virtual functions are equated to zero. class Shape { public: virtual void draw() = 0; }; 34. What are virtual constructors/destructors? Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object. If your class has at least one virtual function, you should have a virtual destructor. This allows you to delete a dynamic object through a baller to a base class object. In absence of this, the wrong destructor will be invoked during deletion of the dynamic object. 35. What is the difference between object based programming and object oriented language? Object-Based Programming usually refers to objects without inheritance and without polymorphism,These languages support abstract data types and not classes,which provide inheritance and polymorphism.however,support both inheritance and polymorphism and they are object-oriented. 36. Is c++ a pure object oriented language? No 37. What is difference between template and macro? In C++ there is a major difference between a template and a macro. A macro is merely a string that the compiler replaces with the value that was defined. E.g. #define STRING_TO_BE_REPLACED "ValueToReplaceWith" A template is a way to make functions independent of data-types. This cannot be accomplished using macros. E.g. a sorting function doesn't have to care whether it's sorting integers or letters since the same algorithm might apply anyway. 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. for example: Macro: #define min(i, j) (i < j ? i : j) template: template<class T> T min (T i, T j) { return i < j ? i : j; }

38. What are C++ storage classes? storage class defines the scope (visibility) and life time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes which can be used in a C++ Program auto register static extern mutable The auto Storage Class The auto storage class is the default storage class for all local variables. { int mount; auto int month; } The example above defines two variables with the same storage class, auto can only be used within functions, i.e. local variables. The register Storage Class The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). { register int miles; } The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. The static Storage Class The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class. #include <iostream> // Function declaration void func(void); static int count = 10; /* Global variable */ main() { while(count--) { func(); } return 0; } // Function definition

void func( void ) { static int i = 5; // local static variable i++; std::cout << "i is " << i ; std::cout << " and count is " << count << std::endl; } When the above code is compiled and executed, it produces following result: i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0 The extern Storage Class The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another files. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. The mutable Storage Class The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override constness. That is, a mutable member can be modified by a const member function. 39. What are storage qualifiers in C++ ? 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 the time, where hardware changes the value of this pointer varia ble 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. 40. What is reference? reference is an alias or an alternative name for an object. All operations applied to a reference act on the object to which the reference refers. The address of a reference is the address of the aliased object. A reference type is defined by placing the reference modifier & after the type specifier. You must initialize all references except function parameters when they are defined. Once defined, a reference cannot be reassigned because

it is an alias to its target. What happens when you try to reassign a reference turns out to be the assignment of a new value to the target. 41. What is passing by reference? Pass by value: The callee function receives a set of values that are to be received by the parameters. All these copies of values have local scope, i.e., they can be accessed only by the callee function. The simplicity and guarantee of unchanging of values passed are the advantages of pass by value. Pass by reference: The callee function receives a set of references which are aliases to variables. If a change is made to the reference variable, the original value (passed by the caller function) will also be changed. All the references are handled by the pointers. Multiple values modification can be done by passing multiple variables. Pass by pointer: The callee function receives a pointer to the variable. The value of the pointer in the caller function can then be modified. The advantages of this process are that the changes are passed back to the caller function and multiple variables can be changed. 42. What is the use of 'using' declaration? In using-declaration, we have using keyword followed by a fully qualified name of a namespace member. This allows using the non-qualified name of that member in the scope of the using-declaration. 43. Name the operators that cannot be overloaded? sizeof, ., .*, .->, ::, ? 44. What is "this" pointer? It is a constant pointer type. It gets created when a non-static member function of a class is called. 45. What is the difference between a pointer and a reference? A reference must be initialized at the time of declaration whereas not needed in case of pointer. A pointer can point to a null object. A reference once initialize to refer to the object can't be reassigned to refer to other whereas reassignment is possible with pointer. 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 46. How do you access the static member of a class? <ClassName>::<StaticMemberName> 47. What are multiple inheritances (virtual inheritance)? What are its advantages and disadvantages? Multiple Inheritance is the process whereby a child can be derived from more than one parent class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships. The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity) when two base classes implement a method with the same name. 48. What is a nested class? Why can it be useful? A nested class is a class enclosed within the scope of another class. For example: // Example 1: Nested class // class OuterClass {

class NestedClass { // ... }; // ... }; Nested classes are useful for organizing code and controlling access and dependencies. Nested classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is public then any code can name it as OuterClass::NestedClass. Often nested classes contain private implementation details, and are therefore made private; in Example 1, if NestedClass is private, then only OuterClass's members and friends can use NestedClass. When you instantiate as outer class, it won't instantiate inside class. 49. Can a copy constructor accept an object of the same class as parameter, instead of reference of the object? No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference. 50. What is the difference between overloading and overriding? Overloading helps to create different behaviors of methods with the same name and scope. For instance we can overload a method to return float values and integer values. Overriding on the other hand changes the behavior of a class to make it behave different than its parent class. 51. Can we have Virtual Constructors? NO 52. Difference between printf and sprintf. sprintf: This Writes formatted data to a character string in memory instead of stdout Syntax of sprintf is: #include <stdio.h> int sprintf (char *string, const char *format [,item [,item]...]); Here String refers to the pointer to a buffer in memory where the data is to be written. Format refers to pointer to a character string defining the format. Each item is a variable or expression specifying the data to write. The value returned by sprintf is greater than or equal to zero if the operation is successful or in other words the number of characters written, not counting the terminating null character is returned. And return a value less than zero if an error occurred. printf: Prints to stdout Syntax for printf is: printf format [argument]... The only difference between sprintf() and printf() is that sprintf() writes data into a character array, while printf() writes data to stdout, the standard output device. 53. How is it possible for two String objects with identical values not to be equal under the == operator? 54. 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.

55. List down the advantages of class templates One C++ Class Template can handle different types of parameters. Compiler generates classes for only the used types. If the template is instantiated for int type, compiler generates only an int version for the c++ template class. Templates reduce the effort on coding for different data types to a single set of code. Testing and debugging efforts are reduced.

56. Write a simple program for finding factorial in C++ ?


int n, result = 1, value = 3; for ( n = 1; n <= value; n++ ) { result *= n; }

57. Inline functions advantages Advantages: 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. 58. Explain the ISA and HASA class relationships. How would you implement each in a class design? A: A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class. 59. What is a mutable member? Mutable keyword allows assigning values to a data member belonging to a class defined as Const or constant. One that can be modified by the class even when the object of the class or the member function doing the modification is const. 60. What is the Standard Template Library? STL stands for Standard Template Library. It is a library of container templates approved by the ANSI committee for inclusion in the standard C++ specification. 61. What is an Iterator class? A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. Something like a pointer. 62. What is a dangling pointer?

When the address of an object is used after its lifetime is over, dangling pointer comes into existence. Some examples of such situations are: Returning the addresses of the automatic variables from a function or using the address of the memory block after it is freed. 63. What are the syntax and semantics for a function template? 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. A function template is similar to a class template and it syntax is as follows: template <class T> Return-type functionName (arguments of type T) { //Body of function with type T wherever appropriate } 64. What are the different types of STL containers? Following are the 3 types of STL containers: 1. Adaptive containers - for e.g. queue, stack 2. Associative containers - for e.g. set, map 3. Sequence containers - for e.g. vector, deque 65. What do you mean by binding? Static vs. dynamic binding 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. 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. 66. True or false: A function should always include a return statement as its last command. False 67. What is the default visibility of a class data member? private 68. What is type casting? Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.

S-ar putea să vă placă și