1. What do you mean by public, private, protected and friendly?
These are access specifiers for class data members and member methods.
1. Public: The data members and methods having public as access specifier can be accessed by the class objects created outside the class.
2. Protected: The data members and methods declared as protected will be accessible to the class methods and the derived class methods only.
3. Private: These data members and methods will be accessible from the class methods only, not from derived classes and not from objects created outside the class.
4. Internal: Some languages define internal as an access specifier which means the data member or method is available to all the classes inside that particular assembly.
5. Friend: A friend class or method can access all data of a class including private and protected data.
2. When is an object created and what is its lifetime?
An object is created when a class is instantiated. This is the time when memory is allocated to the object and the class constructor is called to initialize the data members.
3. What do you mean by multiple inheritance and multilevel inheritance?
Ans 1:
Multiple inheritance refers to a class being derived from two or more classes.
Multilevel inheritance refers to a class inheriting from a parent class which is itself derived from another class.
Multilevel inheritance is supported by all OOPs languages. Multiple inheritance is supported by C++, but not by Java and C#. Java and C# recommend that instead of multiple inheritance the design should be inheriting from one class and implementing other interfaces.
This solves the problems of having to declare 'virtual base classes' as in C++ which arises out of multiple copies of uppermost base class object in a class at inheritance level 3 onwards.
Ans 2:
Multiple: ClassA--extends-->ClassB, ClassA--extends--
>ClassC, ClassA--extends-->ClassD class A can Inherit all
the classes and can have access on all calss' public
properties and functions.
MultiLevel: ClassA-->ClassB-->ClassC-->ClassD and ClassD
will have the accesss on all the properties of its upper
level class like C,B and A
4. What are the main differences between procedure oriented languages and object oriented languages?
Ans 1:
1. Procedural languages enforce sequential processing of instructions. Object oriented languages may implement event driven processing.
2. Procedural languages store all data as global while OOPs languages support data encapsulation -- all related data is stored inside one object and only relevant data is shown to the user.
3. Facilities like function overloading and operator overloading (polymorphism) allow you to use same names and provide different functionality which avoids personalism in naming conventions. These overloaded versions are easy to use and remember.
Ans 2:
In procedural programming the main emphasis is on procedure while in object oriented the data is important part. on the same hand data is more secured in object oriented program.
-----------------------------------------------------------
Procedure Oriented Language:
---------------------------
PO Language is fully concentrates on Procedures/functions/methods. It normally works as a sequence of actions as seen in flowchart or in any algorithm. It follows top-down approach. It totally focuses on methods and not the data which is utilized by methods. In PO languages if data is used by many methods then its declared as global data but there is a problem if we do that, what is that, if we forgot or by mistake if we consume that data in some other method than it comes with problem. Mostly these scenarios happen in large systems.
Example: COBOL, PASCAL, C, FORTRAN etc.
Object Oriented Language:
------------------------
OO concepts says it think about data and bind that data and methods those are manipulating that data into one entity known as object and then utilize that object into system.
Example: C++, Java, C#, VB.Net etc.
There are some fundamental concepts of OO Language which a language has to follow to be a truly OO language.
• OBJECT
• CLASS
• ABSTRACTION
• ENCAPSULATION
• DATA HIDING / INFORMATION HIDING
• INHERITANCE
• POLYMORPHISM
5. What are generic functions and generic classes?
Ans 1:
Generic functions are functions which are not used for any particular datatype..they are useful for anydatatype Ex: if you write code for the Sorting program using templates then the function is useful for any data type to sort...Generic classes are same as generic functions
Ans 2:
Generic functions are the function which return void ptr... (void*)... Generic Classes are template classes...
Basicaly we implement both of them for reusability.. and abstraction..
6. What is the difference between pass by reference and pass by value?
Ans 1:
in pass by referance the parameters are passed as the address of the variables whereas in pass by value the variables are directly passed as parameters
Ans 2:
When using by reference there is no new variable just a alias to the memory address, if this parameters is not constant it is possible to change the content of that address.
When using by value a new variable will be created in memory and it is impossible to change the original content.
7. Why do we use virtual functions?
A function that is defined in a base class but overridden by the derived class is called a virtual function. To create virtual functions precede the function declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited the derived class overrides the virtual function with its own definition. Virtual functions are like member functions however what makes them different is the capability to support run time polymorphism when accessed via a pointer. A base class pointer can point to an object of a derived class. When a base class pointer points to an object of a derived class that contains a virtual function, C++ determines which function version to call based on the type of object pointed by the base class pointer. This is runtime polymorphism as it can be determined at run time. In this way when different objects are pointed to then different versions of virtual functions are executed. Whenever a virtual function is defined all aspects of its prototype should match. Also virtual functions should be non static members of the class and they cannot be friend functions too. E.g. class base { public: virtual void display (); }; class derived: public{ public: virtual void display ();};base *p, b;derived d1, d2;p = &b;p->display (); //calls base class functionp = &d1;p->display (); //calls derived class function
8. What are virtual classes?
Detailed:
Classes can be abstract (and therefore are also base classes, see below). Member functions of classes can be marked virtual.
A class can have member functions that are virtual which means they can be overridden and redefined by sub-classes and allows run time polymorphism. Dr. Bjarne Stroustrup implies in the "The Design and Evolution of C++" that the keyword "virtual" was borrowed from a language called Simula and that virtual is the 'Simula and C++ term for "may be redefined later in a class derived from this one"'.
Now this can be taken to the extreme in that no definition may be provided in the class that initially declares a virtual function - it is a pure virtual function:
class A
{
virtual do_something() = 0; // = 0 => pure virtual function
virtual ~A() {}
};
A consequence of doing this is that you cannot create objects of class A as doing so and calling do_something on the object would result in a call to a non-existent function. You have to derive from A and override do_something providing a function definition (i.e a function implementation) for it. Because you cannot create objects of class A, class A is known as an abstract class. In fact because it has to be used as a base class (that is other classes have to be derived from it to be useful) the proper term is abstract base class (or ABC).
The above is not quite correct. In fact you can provide a definition for a pure virtual function. However this function can only be called directly using compile time (i.e. static) function call despatch, not through the run time polymorphic dynamic despatch mechanism. Anytime you have a pointer or reference to an object of an ABC (abstract base class) like class A and you call a pure virtual function on it that has not been overridden the compiler will probably have to issue a dynamic call using the dynamic call despatch mechanism, which still has a pure (i.e. non-existent) definition for the function and Bang! Your program would crash, or possibly terminate with some message about a pure virtual function being called. For this reason even if you do provide a function definition for a pure virtual member function the class is still abstract and you still cannot create objects of the class or any class derived from it that has not provided definitions for all pure virtual functions.
OK, so you are probably a little confused after that, so I have provided some more information on the calling mechanisms used by C++ below. It is not really directly relevant to your question so only read it if you are interested, and if you do then please ask followup questions if you require clarification as it is not an easy thing to describe (so sorry if it is not 100% clear!).
Before doing so I shall mention briefly that a class used as a base class to some derived class can be specified as a virtual base class. When this occurs a further class deriving from two base classes that both derive from a common virtual base class only get one copy of the common virtual base class:
class Base {};
class Middle1 : public Base {};
class Middle2 : public Base {};
class Derived : public Middle2 : public Middle1 {};
The above class hierarchy does not use virtual base classes and Derived contains two Base sub-objects – one from Middle1 and the other from Middle2. Often this is not at all what is required. What is required is that Derived contain one base sub-object, one Middle1 sub-object and one Middle2 sub-object. This is where virtual base classes come in:
class Base {};
class Middle1 : virtual public Base {};
class Middle2 : virtual public Base {};
class Derived : public Middle2 : public Middle1 {};
Note that the virtual-ality is only applied for a specific use of the Base type – when it is being used as a base class. It does not affect Base itself in other circumstances. For more information see for example Chapter 15 of "The C++ Programming Language 3rd edition" by Bjarne Stroustrup.
You should also check out the C++ FAQ lite at http://www.parashift.com/c++-faq-lite/, for virtual function, ABCs and virtual base classes and loads of other common C++ topics.
Now onto some explanation of function calling in C++. Note that I have made simplifications so as to try to get the main points across.
In general in C++ function calls, whether they are to member functions or free functions (i.e. non member functions) a made using a static despatch mechanism. That is, they are wired up at compile time. It works something like this:
A function implementation, or definition if you like, has an address. The compiler compiles the contents of the function and allocates storage for the code it contains.
If you call the function the compiler makes a direct reference to the address of the function in the code at the call site:
; func();
call 0x00ab0cf0
If you ask for an assembler listing from a compiler (optional output controlled with command line options) and are lucky the listing will use a symbol, here is a real example from a listing produced by MSVC++ 8.0 (the 2005 edition):
call ?FillArray@@YAIPAHI@Z ; FillArray
You can then look for further references to ?FillArray@@YAIPAHI@Z and find its assembler code definition, plus a load of other low level stuff, much of which is probably for the benefit of the linker.
Which brings up the problem of functions called that are defined in other modules. In these cases a similar call instruction is generated, but the symbol used is marked as an external function and it is up to the linker to fill in the details during linking.
In either case the result is the same - the addresses of the functions called in call instructions are fixed by the time the executable has been created. They are static in that when the program is executed these values will not change.
So what happens when you use the dynamic, runtime virtual despatch mechanism by using virtual member functions? Well basically the calls are made indirectly. This is normally (that is practically always) achieved by storing pointers to virtual member functions in a table, called the vtable (v for virtual), for which there is one per class (note: _not_ per object) that requires one. A class requires a vtable if it has at least one virtual member function. However each object of such classes do require access to the class's vtable and so a pointer to it is placed as a hidden data member to each object.
The compiler maintains the entries in this table. As virtual functions are overridden the function pointers to them are updated in the class's vtable. Setting these pointers occurs during construction. Base class parts of an object are initialised before derived class parts so the vtable first gets filled with pointers to base class virtual member function definitions. Later on if a derived class overrides a virtual function the constructor for the derived class part will replace the pointer to the base class function definition with a pointer to the derived class function definition. Note that this is why you cannot call virtual functions during construction and have them call the derived implementation - those parts have not been initialised yet so the vtable contains the base class virtual function definition pointers!
Now you may be able to guess why pure virtual functions are initialised using =0. Yep, the pointer to such functions is notionally a null pointer (or zero), and so a null pointer is placed into the vtable for pure virtual functions and trying to make a call to a function through a null pointer is not a good idea! In fact some compilers place a pointer to a piece of code that causes a pure virtual function call error to be raised instead of a real null pointer.
Here is an example:
First the C++ of a simple virtual function pair of classes:
struct ABC
{
virtual void vfunction() = 0;
virtual ~ABC() {}
};
struct Derived : ABC
{
virtual void vfunction();
};
void Derived::vfunction()
{
std::cout << "Derived::vfunction() called\n";
}
Next a function that calls vfunction dynamically on a reference to ABC:
void Call_VFunction( ABC & object_ref )
{
object.vfunction();
}
And finally some code that calls this function:
int main()
{
Derived d; // Must use a Derived as ABC is abstract
Call_VFunction(d);
}
Now let us look at the dynamic call to Derived::vfunction though the object_ref ABC refernce argument to Call_VFunction.
Here is the simpified assembler:
mov eax, _object_ref$[ebp]
mov edx, [eax]
mov esi, esp
mov ecx, _object_ref$[ebp]
mov eax, [edx]
call eax
Quite complex isn't it?
Some of the lines concern setting up the stack and this pointer for the call:
mov esi, esp
mov ecx, _object_ref$[ebp]
So we can remove them as they are not central to the discussion. This leaves:
mov eax, _object_ref$[ebp]
mov edx, [eax]
mov eax, [edx]
call eax
The sequence goes as follows:
mov eax, _object_ref$[ebp]
Move the value of the object_ref parameter into register eax. This is the address of the Derived object d passed from main. Effectively eax holds a pointer to d.
mov edx, [eax]
Move into register edx the contents at the addess in register eax, which is the first data item in d. This is the pointer to the vtable. Register edx now holds a pointer to the Derived class's vtable.
mov eax, [edx]
Move into eax (again!) the value at the address in edx. This is the address of the first entry in the Derived class's vtable. Register eax now holds a pointer to the Derived::vfunction function.
call eax
Finally! Call the function at the address in eax.
Now the same piece of code will work with another class derived from ABC, say Derived2:
struct Derived2 : ABC
{
virtual void vfunction();
};
void Derived2::vfunction()
{
std::cout << "Derived2::vfunction() called\n";
}
All that happens is that the following are done:
mov eax, _object_ref$[ebp]; load pointer to Derived2 object
mov edx, [eax] ; load pointer to Derived2 vtable
mov eax, [edx] ; load pointer to Derived2::vfunction
call eax ; Call Derived2::vfunction
The same code can call different functions depending on the exact type of the object it is passed. The code does not know at compile time which function it will call, that is only determined dynamically at run time.
It does of course rely on the vtables for all the related types being laid out in a compatible and consistent manner and, for that matter, that the position of the vtable pointer for objects is maintained consistently.
9. Does c++ support multilevel and multiple inheritance?
Yes,
In C++ we can derive a class C from B which is derived from A -- multilevel inheritance.
In C++ we can derive a class D from two base classes A and B -- multiple inheritance. This may cause a problem in case A and B are derived from a single base class say P. When a D's method refers to a public/protected data member of P (the uppermost parent) there are two paths available -- A::var or B::var -- here the compiler gives an error. To avoid this problem A and B need to be 'virtually' derived from P. If they are virtually derived then only one copy of P's data members exist for both A and B objects.
10. What are the advantages of inheritance?
Ans 1:
Inheritance offers the following advantages --
1. Developement model closer to real life object model with hierarchical relationships
2. Reusability -- facility to use public methods of base class without rewriting the same
3. Extensibility -- extending the base class logic as per business logic of the derived class
4. Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class
Ans 2:
In OOPs, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have combined features of both the
classes.
11. When is a memory allocated to a class?
Ans 1:
A class is a template.As Teginder said,it will get allocated memory when u create object of that class.
Ans 2:
When an object is instantiated.
12. What is the difference between declaration and definition?
Answer 1:
You have to declare functions, structures and variable because the compiler needs to know how much memory (or stack space) to reserve for these things.
Function prototype...
int myfunction(int x, char c);
You need a function prototype so the compiler knows how much memory this functions needs to reserve on the stack for the parameters passed to and from the function. (In this case 5 bytes)
A definition is used as a direct replacement...
1. DEFINE MYVALUE 0xef
Wherever the compiler encounters "MYVALUE" it replaces it with the defined value (0xef).
This is useful because if you have to change a value, you just change it in the definition (usually placed at the start of the C file).
Otherwise you have to find every place this value is used and change it manually.
For example: If your software displays it's version number on the screen and in any files it may create, you can use a defintion...
1. DEFINE VERSION V1.01
printf("My Program %s\n", VERSION);
fprintf( fp, "My Program %s\n", VERSION);
When the version number changes, you can just change the definition and the new version number is compiled for every placed it is used.
Answer 2:
The term declaration means (in C) that you are telling the compiler about type, size and in case of function declaration, type and size of its parameters of any variable, or user defined type or function in your program. _No_ space is reserved in memory for any variable in case of declaration. However compiler knows how much space to reserve in case a variable of this type is created.
for example, following are all declarations: extern int a; struct _tagExample { int a; int b; }; int myFunc (int a, int b);
Definition on the other hand means that in additions to all the things that declaration does, space is also reserved in memory. You can say "DEFINITION = DECLARATION + SPACE RESERVATION" following are examples of definition: int a; int b = 0; int myFunc (int a, int b) { return a + b; } struct _tagExample example;
13. What is virtual constructors/destructors?
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.
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even hough they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying he delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.
irtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.
14. What is late bound function call and early bound function call? Differentiate.
Ans 1:
Functions are boud to there address so that they could be executed. if the address of the functions are known durning compile time the compiler binds it, this kind of binding is known as compile time binding or early binding. Where as when we dont know which function needs to be exucuted during compile time (as in case of dynamic polymorphism), compiler uses mechaninsm of virtual table and binds the function address during runtime. this is known as runtime binding or late binding.
Ans 2:
if function or any variable known during the compile time such Binding is known as Early Binding.
if during compile time does not specify which function is bind. such binding known as Late Binding.
Example
--------
Object is best Example of late binding
we are bind object variable at Dynamically when we use the object.
15. How is exception handling carried out in c++?
Exception handling is carried out using try, catch blocks and the throw statement.
Try block includes all code which can result into any exception.
It is followed by one or more catch blocks starting from most specific to least specific. A catch block handling exception of a class type can also handle exceptions of any class in its inheritance hierarchy.
A function can declare a throw (....) declaration saying that it is not going to handle exceptions of the specified types. These exceptions will be thrown to the calling function.
If an exception is unhandled the program will have abnormal termination.
try catch blocks can be nested to any level.
16. When will a constructor executed?
A constructor is executed when an object of a class is getting initialized (constructed)
17. What is Dynamic Polymorphism?
Ans 1:
Dynamic polymorphism is also known as runtime polymorphism.
It is achieved by means of virtual functions.
Depending on the type of object referred by a variable the decision about the method to be called (whether to call base class implementation or the derived class implementation) is taken at runtime. This is dynamic polymorphism.
Ans 2:
in hirarchie, when sub class overrides the super class method then we call that method using the super class reference then which version of method is called is resolved at run time based on the object that the reference refers to is called dynamic polymorphisum or dynamic binding.and also called run time polymorphisum
18. Write a macro for swapping integers.
Ans 1:
main(){ int a,b;scanf("%d,%d"a,b); a^=b;b^=a;a^=b;printf("The values after swap is %d %d",a,b);}
Ans 2:
#define SWAP(a,b) b=a+b-(a=b)
Ans 3:
# define swap(a,b) a = a + b; b = a - b; a = a - b;
Wednesday, December 10, 2008
Subscribe to:
Post Comments (Atom)
1 comment:
Salve
Thanks for highlighting this and indicating about #topic where more study and thought is necessary.
in 16 bit DOS programming, keep() is used to resident a program in memory, but in 32 bit / 64 bit C compiler, how can I use this?If keep() does not work, then what is the alternative function that works?
Great effort, I wish I saw it earlier. Would have saved my day :)
Thank you
Post a Comment