Monday 13 May 2013

C++ Basics


FAQ’s  on C++:
1.      Basic of C++
a)    Procedure  Oriented  Programming
b)    Applications of  C++
c)     Tokens, Expressions and  Control  Structures 
2.      Functionsin C++
a)      Introduction Of Functions
b)      Inline Functions and Function Overloading
3.      Classes and Objects
a)      Introduction of classes and objects
b)       Friend Function
4.      Constructors and Destructors
a)      Introduction of constructors
b)      Copy constructors
c)      Destructors
5.      Operators overloading and Type Conversions
6.      Inheritance: Extending Classes
a)      Types of Inheritance
b)      Virtual Base Classes
c)      Abstract Classes
7. Pointers, Virtual Functions and Polymorphism
8. Managing Console I/O Operations





BASIC OF C++


APPROACH TOWARDS C++:-

1. What is procedure-oriented programming?
Ans:-Procedure oriented programming basically consists of writing a list of instructions (or actions) for the computer to follow,and organizing these instructions into groups known as functions.

Also in procedure oriented programming, the program is divided into procedures that do discrete tasks. Each procedure has its own local data. Parameters are passed between procedures for information communication.


2.What are the characterics of procedure oriented programming?
Ans:-Characteristics are:-

a) Emphasis on doing things (algorithms).
b) Large programs are divided into smaller programs known as functions.
c) Most of the functions share global data.
d) Data move openly around the system from function to function.
e) Employs top-down approach in program design.

3.) What is object oriented  programmming?
Ans:-It is an approach that  provides a way of  modularizing programs(dividing program into modules) by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand.

4.) What are the characteristics of object-oriented programming?
Ans:-Characteristics are:-

a)      Emphasis is on data rather than procedure.
b)      Programs are divided into what are known as functions.
c)      Data structures are designed such that they characterize the objects.
d)      Data is hidden and cannot be accessed by external functions.
e)      Follows bottom-up approach in program design.

5.) What are the advantages of inheritance?
AnsIt 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.
6.)What is Polymorphism?
Ans-Polymorphism is phenomena by which we can make make a method for reuse. Polymorphism is an object oriented term. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form. Polymorphism leads to two important aspects in Object Oriented terminology - First one is function Overloading and second is function overriding. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Overriding refers to the modifications made in the sub class to the inherited methods from the base class to change their behavior.
7.) What are Templates?
Ans-C++ Templates allow u to generate families of functions or classes that can  operate on a variety of different data types, freeing you from the need to create a separate function or class for each type. Using templates, u have the convenience of writing a single generic function or class definition, which the compiler automatically translates into a specific version of the function or class, for each of the different data types that your program actually uses. Many data structures and algorithms can be defined independently of the type of data they work with. You can increase the amount of shared code by separating data-dependent portions from data-independent portions, and templates were introduced to help you do that.
8.) What is abstraction?
Ans:- Abstraction is the basically type of process, It is the process of hiding the details and  exposing only the essential features of a particular concept or object.

9.)Explain why encapsulation is required?
Ans-Encapsulation basically defined as :
> Encapsulation general meaning is information hiding.
> The purpose of efficiency of memory and speed.
> The data and code binds together.
> It is an OOP principle of placing the data and functionality within a single entity.
> it is to protect data from the client using the classes but still allowing the client to access the data, but not modify it.
 
10.)Name some pure object oriented languages.
Ans- Smalltalk, Java, Eiffel, Sather.
11.)What is the use of Microsoft foundation class library?
Ans- The Microsoft Foundation Class Library also called as A Microsoft Foundation Classes or MFC. It is basically a library that wraps portions of the Windows API in C++ classes, and including functionality that enables them to use a default application framework. Classes are defined for many of the handle-managed Windows objects and also for predefined windows and common controls. MFC library would help us reduce the code and development time.
 
 
 
12.)What is the difference between static link library and dynamic link library?
Ans-Basic diff are there :
> Static libraries are linked at compile time.  
> Dynamic libraries are linked at runtime.
 

OVERVIEW OF C++:-

1. What is C++?
Ans:-Releasedin 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 data type 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++ 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++.

2.) What is Difference between C/C++?
Ans-1. In C passing value to a function is "Call by Value" whereas in C++ its "Call by Reference"
2.C does not have a class/object concept. C++ provides data abstraction, data encapsulation, Inheritance and Polymorphism.
3.C++ supports all C syntax. File extension is .c in C while .cpp  in C++.(C++ compiler compiles the files with .c extension but C compiler cannot!)
4.In C structures cannot have functions declarations. In C++ structures are like classes, so declaring functions is legal and allowed.

5.C++ can have inline/virtual functions for the classes.
6.C++ is C with Classes hence C++ ; while in c the closest u can get to an User defined data type is struct and union.
3.) Difference between "C structure" and "C++ structure".
Ans:-Many diff are there :
1. Structure in C defined as limited to within the module and cannot be initialized outside but Structure in C++ can initialize the objects anywhere within the boundaries of the project.
2. C++ have a many methods((Procedures) but in C no methods are there.
3. By default C structure are Public and  C++ structure are private .
      4. C does not support Methods inside structure but C++ does.
 5. In C++ structure we can add functions but in Cstructure we can't.
            6. In C++, structure behaves like class like can add function, and can use  properties on            class as inheritance, virtual,etc, But in C, structure we can have only  data member but not functions.
        7. Structures in c++ doesnot provide datahiding but a class provides.
  8. classes support polymorphism, But Structures don't.

4.)What are the disadvantages of C++?
Ans-

Disadvantages: 1. It's not pure object oriented programming language.
2. Its a Platform dependent
3.C++ does not give excellant graphics as compare to java.
> Its Not case sensitive.
> C++ have Less features as comapred to Java& C#.
> Its Not applicable in web enviornment.
> Does not provide very strong type-checking.
> c++ code is easily prone to errors related to data types, their conversions.
> Does not provide efficient means for garbage collection.
> No built in support for threads.
 
5.)How does a main() function in C++ differ from main() in C?
Ans-In C the default return type of main is void while in C++ the default return type is int.
 
 6)What is difference between visual c++ & ANSI c++ ?
Ans:-

Visual C++ is probably the most popular favored compiler, because of it's history of quality and stability. But in ANSI C++ is a less popular, but is a much more powerful and robust compiler. The IDE is also a lot more powerful than MSVC.
 
7.)Why is iostream better than stdio?
Ans-Iostream is better than stdio like that :
> The <iostream> library offers two major advantages compared to C's <stdio.h>:
it can be extended to support user-defined types. And it's type-safe. If programmer can give a complain about <Isostream> have give a poorer performance and a bloated ,And unintuitive interface.
 
 
 
8.)Why do we need the preprocessor directive #include <iostream>?
Ans:-This is because this directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator <<.
 
9.) What is namespace?
Ans:-Namespaces basically provide a simple method for qualifying element and attribute names used in Extensible Markup Language documents by associating them with namespaces identified by URI references. Its allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name. It is an abstract container providing context for the items. it holds and allowing disambiguation of items having the same name.

TOKENS , EXPRESSIONS AND CONTROL STRUCTURES:-

1.What are tokens?
Ans:-The smallest  individual  units  in a progr am are known as tokens.C++ has following tokens:-
a)Keywords
b)Identifiers
c) Constants
d) Strings
e) Operators
 
2.What do you understand by dynamic initialization of variables?
Ans:-It refers to initialization  run of variables at run time. In C++, a variable  can be initialized at run time at the place of declaration.
 
3.What is a reference variable? What is its major use?
Ans:- A reference variable provides an alias (alternative name) for a previously defined variable.  For ex:-  if we make the variable average a reference to the variable  mean, then both can be used interchangeably to represent that variable.
 
 
 
4.)Explain the scope resolution operator?
Ans-scope resolution operator permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
 
5.) what are manipulators?
Ans-Manipulators are operators that are used to format the data display. The most commonly used manipulators are endl and setw.
 
6.)Name the operators that cannot be overloaded?
Ans:-The Name of operatores are there which can nt be overladed .......
> sizeof,
>  [.] 
> *
> -  
> ::
> ?:
 
 
 
 
7.)What is a modifier?
Ans-A modifier as a modifying function is a member function which changes the value of at least one data member. In other words, we can say an operation that modifies the state of an object. Modifiers are also known as �mutators�.
 
 
8.)    What is the difference between realloc() and free()?
Ans realloc():
> It is used to free the memory in the program.
> This function is used to resize memory.
> realloc() means it giving string variables into the existed memory
free():
> Basically It is a macro. Macro used to deallocate memory.
> free() function is used free the memory which is allocated by malloc(),calloc() functions.
> free() means it empties the array.

9.)    What is the difference between char str, char *str and char* str? Explain the meaning of char* or int* ?
Ans:-Char *str is just a pointer its can't store anything, If we cout or printf() char *str it prints till it finds termination char '';
char str is a char variable which is capable to store one character and store a string also. Its length can be fixed only at run time.Char* is pointer which store address of char variable .

FUNCTIONS IN C++:-

INTRODUCTION OF FUNCTIONS:-
 
1.      What are the advantages of functions prototypes in C++?
Ans:- The function prototype describes the function interface to the compiler by giving details such as the number and the type of arguments and the type of return values.With function prototyping , a template is always used when declaring and defining a function. When a function is called , the compiler uses the template to ensure that proper arguments are passed , and the return value is treated correctly. Any violation in matching the arguments or the return types will be caught by the compiler at the time of compilation itself.
 
2.What is the main advantage of passing arguments by reference?
Ans:- Reference variables in C++ allows us to pass parameters to the functions by reference. When we pass arguments by reference , the ‘formal’arguments in the called function become aliases to the ‘actual’ arguments in the calling function. This means that when the function is working with its own arguments, it is actually working on the original data.
 
3.When do we need to use default arguments in a function?
Ans:-Default arguments are useful in situations where some arguments always have the same value.
 
     4.)What is the difference between declaration and definition?
Ans-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 () // declaratory
{
for(int j=10; j > =0; j--) //function body
      cout << *;
      cout << endl; }





 
INLINE FUNCTIONS AND FUNCTION OVERLAODING:-
 
1.Define inline functions?
Ans:-An inline function is a function that is expanded in line when it is invoked. That is , the compiler replaces the function call with the corresponding function code. All inline functions must be defined before they are called.
 
      2.When will we make a function inline?
      Ans:-To eliminate the cost of calls to small functions , we make the function        inline.
 
3.How does an inline function differ from a preprocessor macro?
Ans:-Inline function is just like a normal function however macros are not really functions and therefore usual error checking does not occur during compilation.
 
     4.What do you mean by overloading of a function?
Ans:-It refers to use of the same function name to create functions that perform a variety of different tasks.
 
        5.)What is function overloading and operator overloading?
Ans-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.
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).
6.)What is the difference between "overloading" and "overriding"?
Ans:
Many Differeces are there-
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters).
Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
overridding is runtime polymorphism while overloading is compile time polymorphism.

CLASSES AND OBJECTS:-
1.Explain the concept of classes?
Ans:- A class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden , if necessary,from external use. When defining a class , we are creating a new abstract data type that can be treated like any other built-in data type.
2.)What is the difference between class and structure?
Ans:-Diff b/w Class and Structure is : 
Class is difined as-
>Class is a successor of Structure. By default all the members inside the class are private.
>Class is the advanced and the secured form of structure.
>Classes are refernce typed.
>Class can be inherited.
>In Class we can initilase the variable during the declaration.
>Class can not be declared without a tag at the first time.
>Class support polymorphism.
Structure difine as :
> In C++ extended the structure to contain functions also. All declarations inside a structure are by default public.
> Structures contains only data while class bind both data and member functions.
> Structure dosen't support the polymorphism, inheritance and initilization.
> Structure is a collection of the different data type.
> Structure is ovrloaded.
> Structures are value type.
> Structure can be declared without a tag at the first time
 
3.What are objects? 
Ans:-Objects are the instance of the class.They are dynamic.They are the basic runtime entities in an object-oriented system.They may represent a person,a place,a bank account,a table of data or any item that the program has to handle.
4.When do we declare a member of a class static?
Ans:-We declare a member of a class as a static to maintain values common to the entire class.A static member can be used as a counter that records the occurrences of all the objects.
 
5.What is public, protected, private?
Ans:-Public variables - that are visible to all classes.
Private variables - that are visible only to the class to which they belong.
Protected variables - that are visible only to the class to which they belong, and any subclasses.
 
6.What are local classes?
Ans:-Classes which are defined and used inside a function or a block are known as local classes. Local classes can use global variables(declared above the function) with the help of scope operator and the static variables declared inside the function but cannot use automatic local variables.

 
 
FRIEND FUNCTION:-
 
1.What is a friend function?
Ans:-The functions that are declared with the keyword friend are known as friend function. A function can be declared as a friend in any number of classes. A friend function, is not a member function, but it has full access rights to the private members of the class.
 
   2.What are the features of the friend function?
  Ans:-Features of the friend function are:-
a) It is not in the scope of the class to which it has been declared as friend.
b) It cannot be called using the object of that class.
c) It can be invoked like a normal function without the help of  any object.
d) Unlike member functions, it cannot  access the member names directly.
e) It can be declared either in the public or the private part of a class without affecting its meaning.
f)   Usually,it has objects as arguments.

 
 
CONSTRUCTORS AND DESTRUCTORS:-
1. What is a constructor?
Ans:-It is a special member function whose task is to initialize the  objects of its class.It is of the same name as the class. It is invoked whenever an object of its associated class is created . It constructs the values of data members of the class.
2.What is a copy constructor?
Ans:-A constructor which can accept a reference to its own class as a parameter is known as the copy constructor.
3.What is a parameterized constructors?
Ans:-The constructors that can take arguments are called parameterized constructors.
4.What do you mean by dynamic initialization of objects?
Ans:-It means the initial value of an object may be provided during run time. It provides flexibility of using different format of data at run time depending upon the situation.
5.What is destructor and what is its role?
Ans:-A destructor is a member function whose name is the same as the class name but is preceded by a tilde. It is used to destroy the objects that have been created by a constructor. A constructor never takes any argument nor does it return any value.
6.Difference between a "assignment operator" and a "copy constructor"
Ans:-many diff are there :
> Assignment operator assign the object of one object to another aftr the 1st object is fully created but in copy constructor it
assign the value of one object to another at the time of its creation .
> The copy constructor is use for initialising a new instance from an old instance, And is called when passing variables by value into functions
or as return values out of functions. but in Assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory.
> Copy constructor  copies a existing object to a non existing object, which we are going to create. Assignment operation can happen between two existing objects.
> The copy constructor is creating a new object. But in The assignment operator has to deal with the existing data in the object.
> Copy constructor creates shallow copy but in assignment operator creates deep copy.
> The copy constructor is called at initialising the object but the assignment operator is used to assign one object to another.
> Copy constructor donot return anything. But in
Assignment operator returns object of same type.
> The copy constructor  initializes uninitialized  memory, But in assigenment operator starts with an existing initialized objects.
> Copy constuctor initialize the object with the another object of same class But assignment operator can be called on objects of different classes .
OPERATOR OVERLOADING
1.What is operator overloading?
Ans:-The mechanism of giving special meanings to an operator is known as operator overloading.

2.Why is it necessary to overload an operator?
Ans:-Operator overloading provides a flexible option for the creation of new definitions for most of the C++ operators. We can almost create a new language of our own by the creative use of the function and operator overloading techniques.





INHERITANCE:EXTENDING CLASSES
1.What does inheritance mean in C++?
Ans:- Inheritance is the process by which objects of one class acquire the properties of objects of another class. It provides the idea of reusability.
2.What are the different forms of inheritance? Give example for each.
Ans:-The different forms of  inheritance are as follows:-
a)      Single Inheritance :- A derived class with only one base class is called single inheritance.
b)      Multiple Inheritance:-A derived class with several base classes is called multiple inheritance.
c)      Hierarchical Inheritance:- The class acting as a base class for different derived classes is known as hierarchical inheritance.
d)      Multilevel Inheritance:-The mechanism of  deriving  a class from another derived class is known as multilevel inheritance.
e)      Hybrid Inheritance:-The mechanism of deriving a class from a base class and two derived classes is known as hybrid inheritance.

    3. What is virtual class and friend class?
Ans:
friend class is the bassically which class used when two or more classes are designed to work together.used to share private data between 2 or
more classes the function declared as freind are not called using any object it is called like normal . But in virtual class is whihc class aids in multiple inheritance, it is used for run time polymorphism when object is linked to procedure call at run time.
4.When should you use multiple inheritance?
Ans:
There are three acceptable answers:- "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.

5.What is an orthogonal base class?
Ans:
Its a normally a base class if two base classes have a no overlapping properties methods they are said to be orthogonal to each other. A class can be derived from these two base classes with no difficulty.

6.What are abstract base classes?
Ans:
Abstract Base Classes are classes which cannot be used to create any objects.

7.What is containership?

Ans:
Containership is bassically type of hierarchy. It can also be called containment hierarchy. In C++ Possessing of objects of other classes in a class is called containership or nesting.

8.How can a base pointer access the members of a derived class?
Ans:
Base pointer is only point to the object of derived class but it cannot access the members of the derived class .
9.Describe the syntax of the single inheritance.
Ans:-class derived-classname : visibility-mode base-class-name
{
……//
…..//   members of derived class
….//
};
     10.What is a virtual base class?
    Ans:-Multipath inheritance may lead to duplication of inherited members from   base class.This may be avoided by making the common base class as virtual base class.





POINTERS,VIRTUAL FUNCTIONS AND POLYMORPHISM


1.What is Pure Virtual Function? Why and when it is used ?
Answer: The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.

This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.


2.How Virtual functions call up is maintained?
Answer: Through Look up tables added by the compile to every class image. This also leads to performance penalty.

3.Why are member functions not virtual by default?
Answer: Because many classes are not designed to be used as base classes.

Also, objects of a class with a virtual function require space needed by
the virtual function call mechanism - typically one word per object. This
overhead can be significant, and can get in the way of layout
compatibility with data from other languages.

4.What is the role of this pointer?
Ans:-this is a pointer that points to the object for which this function was called. This unique pointer is automatically passed to a member function when it is called.The pointer this acts as an implicit argument to all the member functions.

MANAGING CONSOLE I/O OPERATIONS

1.What is stream?
Ans:-A stream is a sequence of bytes. Its acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent.

2.Why is it necessary to include the file iostream in all your programs?
Ans:-The stream classes used for input and output operations are declared in the header file iostream.Therefore it is necessary to include the file iostream.






REFERENCES:-
book-ebalaguruswamy






.













































2 comments: