C++ Interview Questions

Q: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?
A: There is nothing like Virtual Constructor. The constructor can’t be virtual as the constructor is a code which is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.

Q: What is Constructor ?
A: Constructor creates an object and initializes it. It also creates V-Table for virtual functions. It is different from other methods in a class.

Q: What about Virtual Destructor?
A: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object caller is calling to, proper destructor will be called.
Q: What is the difference between a copy constructor and an overloaded assignment operator?
A: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Q: Can a constructor throws an exception? How to handle the error when the constructor fails?
A: The constructor never throws an error.

Q: What is default constructor?
A: Constructor with no arguments or all the arguments has default values.

Q: What is default (Implicit) copy constructor?
A: Constructor which initializes it's object member variables (by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.
Examples:
(a) Boo Obj1(10); // calling Boo constructor
(b) Boo Obj2(Obj1); // calling boo copy constructor
(c) Boo Obj2 = Obj1;// calling boo copy constructor

Q: When is copy constructors called?
A: Copy constructors are called in following cases:
(a) When a function returns an object of that class by value
(b) When the object of that class is passed by value as an argument to a function
(c) When you construct an object based on another object of the same class
(d) When compiler generates a temporary object

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
A: 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.

Q: What is conversion constructor?
A: constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion.

Example:
class Boo
{
public:
Boo( int i );
};
Boo BooObject = 10 ; // assigning int 10 Boo object

Q:What is conversion operator??
A:class can have a public method for specific data type conversions.

For example:
class Boo
{
double value;
public:
Boo(int i )
operator double()
{
return value;
}
};

Boo BooObject;
double i = BooObject; // assigning object to variable i of type double. now conversion operator gets called to assign the value.

Q: How can I handle a constructor that fails?
A: throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

Q: How can I handle a destructor that fails?
A: Write a message to a log-_le. But do not throw an exception. The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding. During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bare) { handler? There is no good answer:either choice loses information. So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you're dead.

Q: What is Virtual Destructor?
A: Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes. if someone will derive from your class, and if someone will say "new Derived", where "Derived" is derived from your class, and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's type is your class.

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
A: 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.

Q: What's the order that local objects are destructed?
A: In reverse order of construction: First constructed, last destructed. In the following example, b's destructor will be executed first, then a's destructor:
void userCode()
{
Fred a;
Fred b;
...
}

Q: What's the order that objects in an array are destructed?
A: In reverse order of construction: First constructed, last destructed. In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:
void userCode()
{
Fred a[10];
...
}

C++ portability rules

Labels: , | 0 comments

12. Don't put extra top-level semi-colons in code.

Non-portable example:

int
A::foo()
{
};

This is another problem that seems to show up more on C++ than C code. This problem is really a bit of a drag. That extra little semi-colon at the end of the function is ignored by most compilers, but it is not permitted by the standard and it makes some compilers report errors (in particular, gcc 3.4, and also perhaps old versions of the AIX native compiler). Don't do it.
Portable example:

int
A::foo()
{
}

13. C++ filename extension is .cpp.

This one is another plain annoying problem. What's the name of a C++ file? file.cpp, file.cc, file.C, file.cxx, file.c++, file.C++? Most compilers could care less, but some are very particular. We have not been able to find one file extension which we can use on all the platforms we have ported Mozilla code to. For no great reason, we've settled on file.cpp, probably because the first C++ code in Mozilla code was checked in with that extension. Well, it's done. The extension we use is .cpp. This extension seems to make most compilers happy, but there are some which do not like it. On those systems we have to create a wrapper for the compiler (see STRICT_CPLUSPLUS_SUFFIX in ns/config/rules.mk and ns/build/*), which actually copies the file.cpp file to another file with the correct extension, compiles the new file, then deletes it. If in porting to a new system, you have to do something like this, make sure you use the #line directive so that the compiler generates debug information relative to the original .cpp file.

14. Don't mix varargs and inlines.

Non-portable example:

class FooBar {
void va_inline(char* p, ...) {
// something
}
};

The subject says it all, varargs and inline functions do not seem to mix very well. If you must use varargs (which can cause portability problems on their own), then ensure that the vararg member function is a non-inline function.
Portable example:

// foobar.h
class FooBar {
void
va_non_inline(char* p, ...);
};

// foobar.cpp
void
FooBar::va_non_inline(char* p, ...)
{
// something
}

15. Don't use initializer lists with objects.

Non-portable example:

FooClass myFoo = {10, 20};

Some compilers won't allow this syntax for objects (HP-UX won't), actually only some will allow it. So don't do it. Again, use a wrapper function, see Don't use static constructors.
Always have a default constructor.

Always have a default constructor, even if it doesn't make sense in terms of the object structure/hierarchy. HP-UX will barf on statically initialized objects that don't have default constructors.

C++ portability rules

Labels: , | 0 comments

6. Don't use namespace facility.


Support of namespaces (through the namespace and using keywords) is a relatively new C++ feature, and not supported in many compilers. Don't use it.


7. main() must be in a C++ file.


The first C++ compiler, Cfront, was in fact a very fancy preprocessor for a C compiler. Cfront reads the C++ code, and generates C code that would do the same thing. C++ and C startup sequences are different (for example static constructor functions must be called for C++), and Cfront implements this special startup by noticing the function called "main()", converting it to something else (like "__cpp__main()"), adding another main() that does the special C++ startup things and then calls the original function. Of course for all this to work, Cfront needs to see the main() function, hence main() must be in a C++ file. Most compilers lifted this restriction years ago, and deal with the C++ special initialization duties as a linker issue. But there are a few commercial compilers shipping that are still based on Cfront: HP, and SCO, are examples.


So the workaround is quite simple. Make sure that main() is in a C++ file. On the Unix version of Mozilla, we did this by adding a new C++ file which has only a few lines of code, and calls the main main() which is actually in a C file.


8. Use the common denominator between members of a C/C++ compiler family.


For many of the compiler families we use, the implementation of the C and C++ compilers are completely different, sometimes this means that there are things you can do in the C language, that you cannot do in the C++ language on the same machine. One example is the 'long long' type. On some systems (IBM's compiler used to be one, but I think it's better now), the C compiler supports long long, while the C++ compiler does not. This can make porting a pain, as often times these types are in header files shared between C and C++ files. The only thing you can do is to go with the common denominator that both compilers support. In the special case of long long, we developed a set of macros for supporting 64 bit integers when the long long type is not available. We have to use these macros if either the C or the C++ compiler does not support the special 64 bit type.


9. Don't put C++ comments in C code.


The quickest way to raise the blood pressure of a Netscape Unix engineer is to put C++ comments (// comments) into C files. Yes, this might work on your Microsoft Visual C compiler, but it's wrong, and is not supported by the vast majority of C compilers in the world. Just do not go there.


Many header files will be included by C files and included by C++ files. We think it's a good idea to apply this same rule to those headers. Don't put C++ comments in header files included in C files. You might argue that you could use C++ style comments inside #ifdef __cplusplus blocks, but we are not convinced that is always going to work (some compilers have weird interactions between comment stripping and pre-processing), and it hardly seems worth the effort. Just stick to C style /**/ comments for any header file that is ever likely to be included by a C file.


10. Don't put carriage returns in XP code.


While this is not specific to C++, we have seen this as more of an issue with C++ compilers, see Use the common denominator between members of a C/C++ compiler family. In particular, it causes bustage on at least the IRIX native compiler.


On unix systems, the standard end of line character is line feed ('\n'). The standard on many PC editors is carriage return and line feed ("\r\n"), while the standard on Mac is carriage return ("\r"). The PC compilers seem to be happy either way, but some Unix compilers just choke when they see a carriage return (they do not recognize the character as white space). So, we have a rule that you cannot check in carriage returns into any cross platform code. This rule is not enforced on the Windows front end code, as that code is only ever compiled on a PC. The Mac compilers seem to be happy either way, but the same rule applies as for the PC - no carriage returns in cross platform code.


MacCVS, WinCVS, and cygwin CVS when configured to use DOS line endings automatically convert to and from platform line endings, so you don't need to worry. However, if you use cygwin CVS configured for Unix line endings, or command line cvs on Mac OS X, you need to be somewhat careful.


11. Put a new line at end-of-file.


Not having a new-line char at the end of file breaks .h files with the Sun WorkShop compiler and it breaks .cpp files on HP.

C++ portability rules

Labels: , | 0 comments

1. Be very careful when writing C++ templates.

Don't use C++ templates unless you do only things already known to be portable because they are already used in Mozilla (such as patterns used by nsCOMPtr or CallQueryInterface) or are willing to test your code carefully on all of the compilers we support and be willing to back it out if it breaks.

2. Don't use static constructors.

Non-portable example:

FooBarClass static_object(87, 92);

void
bar()
{
if (static_object.count > 15) {
...
}
}

Static constructors don't work reliably either. A static initialized object is an object which is instanciated at startup time (just before main() is called). Usually there are two components to these objects. First there is the data segment which is static data loaded into the global data segment of the program. The second part is a initializer function that is called by the loader before main() is called. We've found that many compilers do not reliably implement the initializer function. So you get the object data, but it is never initialized. One workaround for this limitation is to write a wrapper function that creates a single instance of an object, and replace all references to the static initialized object with a call to the wrapper function:
Portable example:

static FooBarClass* static_object;

FooBarClass*
getStaticObject()
{
if (!static_object)
static_object =
new FooBarClass(87, 92);
return static_object;
}

void
bar()
{
if (getStaticObject()->count > 15) {
...
}
}

3. Don't use exceptions.

Exceptions are another C++ feature which is not very widely implemented, and as such, their use is not portable C++ code. Don't use them. Unfortunately, there is no good workaround that produces similar functionality.

One exception to this rule (don't say it) is that it's probably ok, and may be necessary to use exceptions in some machine specific code. If you do use exceptions in machine specific code you must catch all exceptions there because you can't throw the exception across XP (cross platform) code.

4. Don't use Run-time Type Information.

Run-time type information (RTTI) is a relatively new C++ feature, and not supported in many compilers. Don't use it.

If you need runtime typing, you can achieve a similar result by adding a classOf() virtual member function to the base class of your hierarchy and overriding that member function in each subclass. If classOf() returns a unique value for each class in the hierarchy, you'll be able to do type comparisons at runtime.

5. Don't use C++ standard library features, including iostream

Using C++ standard library features involves significant portability problems because newer compilers require the use of namespaces and of headers without .h, whereas older compilers require the opposite. This includes iostream features, such as cin and cout.

Furthermore, using the C++ standard library imposes difficulties on those attempting to use Mozilla on small devices.

There is one exception to this rule: it is acceptable to use placement new. To use it, include the standard header by writing #include NEW_H.

C optimisations

Labels: , | 0 comments

Loop jamming

Never use two loops where one will suffice:
for(i=0; i<100; i++)
{
stuff();
}

for(i=0; i<100; i++)
{
morestuff();
}
It would be better to do:
for(i=0; i<100; i++)
{
stuff();
morestuff();
}
Note, however, that if you do a lot of work in the loop, it might not fit into your processor's instruction cache. In this case, two separate loops may actually be faster as each one can run completely in the cache.

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

Faster for() loops

Simple but effective.
Ordinarily, you would code a simple for() loop like this:
for( i=0; i<10; i++){ ... }
i loops through the values 0,1,2,3,4,5,6,7,8,9
If you don't care about the order of the loop counter, you can do this instead:

for( i=10; i--; ) { ... }
Using this code, i loops through the values 9,8,7,6,5,4,3,2,1,0, and the loop should be faster.
This works because it is quicker to process "i--" as the test condition, which says "is i non-zero? If so, decrement it and continue.".
For the original code, the processor has to calculate "subtract i from 10. Is the result non-zero? if so, increment i and continue.". In tight loops, this make a considerable difference.
The syntax is a little strange, put is perfectly legal. The third statement in the loop is optional (an infinite loop would be written as "for( ; ; )" ). The same effect could also be gained by coding:

for(i=10; i; i--){}
or (to expand it further)
for(i=10; i!=0; i--){}
The only things you have to be careful of are remembering that the loop stops at 0 (so if you wanted to loop from 50-80, this wouldn't work), and the loop counter goes backwards.It's easy to get caught out if your code relies on an ascending loop counter.

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

switch() instead of if...else...

For large decisions involving if...else...else..., like this:
if( val == 1)
dostuff1();
else if (val == 2)
dostuff2();
else if (val == 3)
dostuff3();
it may be faster to use a switch:
switch( val )
{
case 1: dostuff1(); break;

case 2: dostuff2(); break;

case 3: dostuff3(); break;
}
In the if() statement, if the last case is required, all the previous ones will be tested first. The switch lets us cut out this extra work. If you have to use a big if..else.. statement, test the most likely cases first.

C optimisations

Using array indices

If you wished to set a variable to a particular character, depending upon the value of something, you might do this :

switch ( queue ) {
case 0 : letter = 'W';
break;
case 1 : letter = 'S';
break;
case 2 : letter = 'U';
break;
}
or maybe
if ( queue == 0 )
letter = 'W';
else if ( queue == 1 )
letter = 'S';
else
letter = 'U';
A neater ( and quicker ) method is to simply use the value as an index into a character array, eg.
static char *classes="WSU";

letter = classes[queue];
--------------------------------------------------------------------------------
Aliases

Consider the following:
void func1( int *data )
{
int i;

for(i=0; i<10;>
{
somefunc2( *data, i);
}
}
Even though "*data" may never change, the compiler does not know that somefunc2() did not alter it, and so the program must read it from memory each time it is used - it may be an alias for some other variable that is altered elsewhere. If you know it won't be altered, you could code it like this instead:
void func1( int *data )
{
int i;
int localdata;

localdata = *data;
for(i=0; i<10;>
{
somefunc2( localdata, i);
}
}
This gives the compiler better opportunity for optimisation.

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

Integers

Use unsigned ints instead of ints if you know the value will never be negative. Some processors can handle unsigned integer arithmetic considerably faster than signed ( this is also good practise, and helps make for self-documenting code).
So the best declaration for an int variable in a tight loop would be

register unsigned int var_name;

(although it is not guaranteed that the compiler will take any notice of "register", and "unsigned" may make no difference to the processor.)

Remember, integer arithmetic is much faster than floating-point arithmetic, as it can be usually be done directly by the processor, rather than relying on external FPUs or floating point maths libraries. If you only need to be accurate to two decimal places (e.g. in a simple accounting package), scale everything up by 100, and convert it back to floating point as late as possible.

C++ Optimizations

Avoid Expensive Operations
Addition is cheaper than multiplication and multiplication is cheaper than division. Factor out expensive operations whereever possible.

Initialize on Declaration
Whereever possible, initialize variables at the time they're declared. For example,

TMyClass myClass = data;

is faster than

TMyClass myClass;
myClass = data;

Declaration then initialization invokes the object's default constructor then its assignment operator. Initializing in the declaration invokes only its copy constructor.

Pass By Reference
Always try to pass classes by reference rather than by value. For example, use

void foo(TMyClass &myClass)

rather than

void foo(TMyClass myClass)

Delay Variable Declarations
Leave variable declarations right until the point when they're needed. Remember that when a variable is declared its constructor is called. This is wasteful if the variable is not used in the current scope.

Use 'op='
Wherever possible, use 'op=' in favour of 'op'. For example, use

myClass += value;

rather than

myClass = myClass + value;

The first version is better than the second because it avoids creating a temporary object.

Inline Small Functions
Small, performance critical functions should be inlined using the inline keyword, e.g.,

inline void foo()

This causes the compiler to duplicate the body of the function in the place it was called from. Inlining large functions can cause cache misses resulting in slower execution times.

Use Nameless Classes
Whereever possible, use nameless classes. For example,

foo(TMyClass("abc"));

is faster than

TMyClass myClass("abc");
foo(myClass);

because, in the first case, the parameter and the class share memory.

C++ Optimizations

These optimizations are fairly easy to apply to existing code and in some cases can result in big speedups. Remember the all-important maxim though, the fastest code is code that isn't called.

Use Initialization Lists
Always use initialization lists in constructors. For example, use

TMyClass::TMyClass(const TData &data) : m_Data(data)
{
}

rather than

TMyClass::TMyClass(const TData &data)
{
m_Data = data;
}

Without initialization lists, the variable's default constructor is invoked behind-the-scenes prior to the class's constructor, then its assignment operator is invoked. With initialization lists, only the copy constructor is invoked.

Optimize For Loops
Whereever possible, count down to zero rather than up to n. For example, use

for (i = n-1; i >= 0; --i)

rather than

for (i = 0; i <>

The test is done every iteration and it's faster to test against zero than anything else. Note also that

++i

is faster than

i++

when it appears in the third part of the for loop statement.

Use 'int'
Always use the int data type instead of char or short wherever possible. int is always the native type for the machine.

Make Local Functions Static
Always declare local functions as static, e.g.,

static void foo()

This means they will not be visible to functions outside the .cpp file, and some C++ compilers can take advantage of this in their optimizations.

Optimize If Statements
Factor out jumps. For example, use

bar();
if (condition)
{
undoBar();
foo();
}
rather than

if (condition)
{
foo();
}
else
{
bar();
}

Use a profiler and good judgement to decide if undoing the bar() operation is faster than jumping.

Optimize Switch Statements
Put the most common cases first.

Interview FAQs : C++ (Answers End of Post)

1) Which is the parameter that is added to every non-static member function when it is called?
---------------------------------------------------------------------------------------
2)
class base
{
public:
int bval;
base(){ bval=0;}
};
class deri:public base
{
public:
int dval;
deri(){ dval=1;}
};
void SomeFunc(base *arr,int size)
{
for(int i=0; i <>bval;
cout << endl; } int main() { base BaseArr[5]; SomeFunc(BaseArr,5); deri DeriArr[5]; SomeFunc(DeriArr,5); }
---------------------------------------------------------------------------------------
3) 
class base { public: void baseFun(){ cout << "from base" <<>baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
Deri deriObject;
SomeFunc(&deriObject);
}
---------------------------------------------------------------------------------------
4)
class base
{
public:
virtual void baseFun(){ cout << "from base" <<>baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
Deri deriObject;
SomeFunc(&deriObject);
}
---------------------------------------------------------------------------------------
5)
class some
{
public:
~some()
{
cout << "some's destructor" << endl; } }; void main() { some s; s.~some(); } ---------------------------------------------------------------------------------------
6) #include class fig2d { int dim1; int dim2; public: fig2d() { dim1=5; dim2=6;} virtual void operator<<(ostream & rhs); }; void fig2d::operator<<(ostream &rhs) { rhs <<>dim1 <<" "<<<" "; } /*class fig3d : public fig2d { int dim3; public: fig3d() { dim3=7;} virtual void operator << (ostream &rhs); }; void fig3d::operator << (ostream &rhs) { fig2d::operator <<(rhs); rhs <<>dim3;
}
*/

void main()
{
fig2d obj1;
// fig3d obj2;
obj1 << cout; // obj2 << cout; }
---------------------------------------------------------------------------------------
7) Class opOverload { Public: bool operator==(opOverload temp); }; bool opOverload::operator==(opOverload temp) { if(*this == temp ) { cout << "The both are same objects\n"; return true; } else { cout << "The both are different\n"; return false; } } void main() { opOverload a1, a2; a1= =a2; }
---------------------------------------------------------------------------------------
8) Class complex { double re; double im; public: complex() : re(1),im(0.5) {} bool operator==(complex &rhs); operator int(){} }; bool complex::operator == (complex &rhs) { if((this->re == rhs.re) && (this->im == rhs.im))
return true;
else
return false;
}
int main()
{
complex c1;
cout << c1;
}
---------------------------------------------------------------------------------------
9)
Class complex
{
double re;
double im;
public:
complex() : re(0),im(0) {}
complex(double n) { re=n,im=n;};
complex(int m,int n) { re=m,im=n;}
void print() { cout << re; cout << im;}
};
void main()
{
complex c3;
double i=5;
c3 = i;
c3.print();
}
---------------------------------------------------------------------------------------
C++ Answer
---------------------------------------------------------------------------------------
1. ‘this’ pointer

00000

2. 01010

3. from base
from base

4. from base
from Derived

5. some's destructor
some's destructor

6. 5 6

7. Runtime Error: Stack Overflow

8. Garbage value

9. 5,5

C Inteview Question

Question :: Read below code and answer the following questions.

 

LINE

Contains

50

char * b, q, *r;

200

b=getbuf();

201

q = *b;

212

r= anotherfunction(b);

213-300

/* we want to use ‘q’ and  ‘r’ here*/

2000

char * getbuf()

2001

{

2002

   char buff[8];

2003-2050

/* unspecified, buff defined here *./

2051

  return (char *) buff;

2052

}




1. What will be in variable ‘q’ after line 201 is executed? Under what conditions might this not be so?
Answer:


2. Is there an alternative, but equivalent, way to write line 2000? If so, what is it?
Answer:



3. Is getbuf() a reasonable function? 
Answer:



4. Will getbuf() execute at all?
Answer:



5. Please comment on line 2051.
Answer:



6. Is getbuf() good practice, and why?
Answer:



7. What line not given should be provided for compilation?
Answer :



(Suggestions and comments are welcome)

DBMS Interview Questions & Answers

13. What is "transparent DBMS"?
Ans. It is one, which keeps its Physical Structure hidden from user.

14. Brief theory of Network, Hierarchical schemas and their properties
Ans. Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a hierarchical schema uses a tree data structure example for such a system is IMS.

15. What is a query?
Ans. A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language.

16. What do you mean by Correlated subquery?
Ans. Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery.
A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a non-correlated subquery.
E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST.CNUM = ORDER.CNUM)

17. What are the primitive operations common to all record management systems?
Ans. Addition, deletion and modification.

18. Name the buffer in which all the commands that are typed in are stored
Ans. ‘Edit’ Buffer

19. What are the unary operations in Relational Algebra?
Ans. PROJECTION and SELECTION.

20. Are the resulting relations of PRODUCT and JOIN operation the same?
Ans. No.
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.

21. What is RDBMS KERNEL?
Ans. Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database
You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures.

22. Name the sub-systems of a RDBMS
Ans. I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management

23. Which part of the RDBMS takes care of the data dictionary? How
Ans. Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel.

24. What is the job of the information stored in data-dictionary?
Ans. The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage location.

25. How do you communicate with an RDBMS?
Ans. You communicate with an RDBMS using Structured Query Language (SQL)

DBMS Interview Questions & Answers

16. In mapping of ERD to DFD
Ans. a) entities in ERD should correspond to an existing entity/store in DFD
b) entity in DFD is converted to attributes of an entity in ERD
c) relations in ERD has 1 to 1 correspondence to processes in DFD
d) relationships in ERD has 1 to 1 correspondence to flows in DFD

(a) entities in ERD should correspond to an existing entity/store in DFD

17. A dominant entity is the entity
Ans. a) on the N side in a 1 : N relationship
b) on the 1 side in a 1 : N relationship
c) on either side in a 1 : 1 relationship
d) nothing to do with 1 : 1 or 1 : N relationship

(b) on the 1 side in a 1 : N relationship

18. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By
Ans. CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMER
The above is
a) Not an error
b) Error - the string in single quotes 'NORTH' and 'SOUTH'
c) Error - the string should be in double quotes
d) Error - ORDER BY clause

(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS

19. What is Storage Manager?
Ans. It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system.
20. What is Buffer Manager?
Ans. It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory.

21. What is Transaction Manager?
Ans. It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting.

22. What is File Manager?
Ans. It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk.

23. What is Authorization and Integrity manager?
Ans. It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data.
24. What are stand-alone procedures?
Ans. Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution.

25. What are cursors give different types of cursors.
Ans. PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors
? Implicit
? Explicit

26. What is cold backup and hot backup (in case of Oracle)?
Ans. ? Cold Backup:
It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy.
If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.
? Hot Backup:
Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.
So different means of backing up database must be used — the hot backup. Issue a SQL command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to backed up. The users can continue to make full use of the files, including making changes to the data. Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to copy those files to the desired backup destination.
The database must be running in ARCHIVELOG mode for the hot backup option.
If a data loss failure does occur, the lost database files can be restored using the hot backup and the online and offline redo logs created since the backup was done. The database is restored to the most consistent state without any loss of committed transactions.

27. What are Armstrong rules? How do we say that they are complete and/or sound
Ans. The well-known inference rules for FDs
? Reflexive rule :
If Y is subset or equal to X then X Y.
? Augmentation rule:
If X Y then XZ YZ.
? Transitive rule:
If {X Y, Y Z} then X Z.
? Decomposition rule :
If X YZ then X Y.
? Union or Additive rule:
If {X Y, X Z} then X YZ.
? Pseudo Transitive rule :
If {X Y, WY Z} then WX Z.
Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of FDs satisfy these three. They are called complete because using these three rules we can generate the rest all inference rules.

28. How can you find the minimal key of relational schema?
Ans. Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency.
Algo. I Determining X+, closure for X, given set of FDs F
1. Set X+ = X
2. Set Old X+ = X+
3. For each FD Y Z in F and if Y belongs to X+ then add Z to X+
4. Repeat steps 2 and 3 until Old X+ = X+

Algo.II Determining minimal K for relation schema R, given set of FDs F
1. Set K to R that is make K a set of all attributes in R
2. For each attribute A in K
a. Compute (K – A)+ with respect to F
b. If (K – A)+ = R then set K = (K – A)+


29. What do you understand by dependency preservation?
Ans. Given a relation R and a set of FDs F, dependency preservation states that the closure of the union of the projection of F on each decomposed relation Ri is equal to the closure of F. i.e.,
((?R1(F)) U … U (?Rn(F)))+ = F+
if decomposition is not dependency preserving, then some dependency is lost in the decomposition.
30. What is meant by Proactive, Retroactive and Simultaneous Update.
Ans. Proactive Update:
The updates that are applied to database before it becomes effective in real world .
Retroactive Update:
The updates that are applied to database after it becomes effective in real world .
Simulatneous Update:
The updates that are applied to database at the same time when it becomes effective in real world .

C++ Interview Questions & Answers

Q: What is Virtual Destructor?
A: Using virtual destructors, you can destroy objects without knowing their type - the correct
destructor for the object is invoked using the virtual function mechanism. Note that destructors
can also be declared as pure virtual functions for abstract classes. if someone will derive from
your class, and if someone will say "new Derived", where "Derived" is derived from your class,
and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's
type is your class.

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference
of the object?
A: 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.

Q: What's the order that local objects are destructed?
A: In reverse order of construction: First constructed, last destructed.
In the following example, b's destructor will be executed first, then a's destructor:
void userCode()
{
Fred a;
Fred b;
...
}

Q: What's the order that objects in an array are destructed?
A: In reverse order of construction: First constructed, last destructed.
In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:
void userCode()
{
Fred a[10];
...
}

Q: Can I overload the destructor for my class?
A: No.
You can have only one destructor for a class Fred. It's always called Fred::~Fred(). It never takes
any parameters, and it never returns anything.
You can't pass parameters to the destructor anyway, since you never explicitly call a destructor
(well, almost never).

Q: Should I explicitly call a destructor on a local variable?
A: No!
The destructor will get called again at the close } of the block in which the local was created.
This is a guarantee of the language; it happens automagically; there's no way to stop it from
happening. But you can get really bad results from calling a destructor on the same object a
second time! Bang! You're dead!

Q: What if I want a local to "die" before the close } of the scope in which it was created? Can I
call a destructor on a local if I really want to?
A: No! [For context, please read the previous FAQ].
Suppose the (desirable) side effect of destructing a local File object is to close the File. Now
suppose you have an object f of a class File and you want File f to be closed before the end of the
scope (i.e., the }) of the scope of object f:
void someCode()
{
File f;
...insert code that should execute when f is still open...
We want the side-effect of f's destructor here!
...insert code that should execute after f is closed...
}
There is a simple solution to this problem. But in the mean time, remember: Do not explicitly
call the destructor!

Q: OK, OK already; I won't explicitly call the destructor of a local; but how do I handle the
above situation?
A: Simply wrap the extent of the lifetime of the local in an artificial block {...}:
void someCode()
{
{
File f;
...insert code that should execute when f is still open...
} f's destructor will automagically be called here!
...insert code here that should execute after f is closed...}

DBMS Interview Questions & Ans

1. Define SQL and state the differences between SQL and other conventional programming Languages ?
Ans. SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them.

2. Name the three major set of files on disk that compose a database in Oracle
Ans. There are three major sets of files on disk that compose a database. All the files are binary. These are
? Database files
? Control files
? Redo logs
The most important of these are the database files where the actual data resides. The control files and the redo logs support the functioning of the architecture itself.
All three sets of files must be present, open, and available to Oracle for any data on the database to be useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the database using a backup, if there is one.

3. What is an Oracle Instance?
Ans. The Oracle system processes, also known as Oracle background processes, provide functions for the user processes—functions that would otherwise be done by the user processes themselves
Oracle database-wide system memory is known as the SGA, the system global area or shared global area. The data and control structures in the SGA are shareable, and all the Oracle background processes and user processes can use them.
The combination of the SGA and the Oracle background processes is known as an Oracle instance

4. What are the four Oracle system processes that must always be up and running for the database to be useable ?
Ans. The four Oracle system processes that must always be up and running for the database to be useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process Monitor).

5. What are database files, control files and log files. How many of these files should a database have at least? Why?
Ans. Database Files
The database files hold the actual data and are typically the largest in size. Depending on their sizes, the tables (and other objects) for all the user accounts can go in one database file—but that's not an ideal situation because it does not make the database structure very flexible for controlling access to storage for different users, putting the database on different disk drives, or backing up and restoring just part of the database.
You must have at least one database file but usually, more than one files are used. In terms of accessing and using the data in the tables and other objects, the number (or location) of the files is immaterial.
The database files are fixed in size and never grow bigger than the size at which they were created
Control Files
The control files and redo logs support the rest of the architecture. Any database must have at least one control file, although you typically have more than one to guard against loss. The control file records the name of the database, the date and time it was created, the location of the database and redo logs, and the synchronization information to ensure that all three sets of files are always in step. Every time you add a new database or redo log file to the database, the information is recorded in the control files.
Redo Logs
Any database must have at least two redo logs. These are the journals for the database; the redo logs record all changes to the user objects or system objects. If any type of failure occurs, the changes recorded in the redo logs can be used to bring the database to a consistent state without losing any committed transactions. In the case of non-data loss failure, Oracle can apply the information in the redo logs automatically without intervention from the DBA.
The redo log files are fixed in size and never grow dynamically from the size at which they were created.

6. What is ROWID?
Ans. The ROWID is a unique database-wide physical address for every row on every table. Once assigned (when the row is first inserted into the database), it never changes until the row is deleted or the table is dropped.
The ROWID consists of the following three components, the combination of which uniquely identifies the physical storage location of the row.
? Oracle database file number, which contains the block with the rows
? Oracle block address, which contains the row
? The row within the block (because each block can hold many rows)
The ROWID is used internally in indexes as a quick means of retrieving rows with a particular key value. Application developers also use it in SQL statements as a quick way to access a row once they know the ROWID

7. What is Oracle Block? Can two Oracle Blocks have the same address?
Ans. Oracle "formats" the database files into a number of Oracle blocks when they are first created—making it easier for the RDBMS software to manage the files and easier to read data into the memory areas.
The block size should be a multiple of the operating system block size. Regardless of the block size, the entire block is not available for holding data; Oracle takes up some space to manage the contents of the block. This block header has a minimum size, but it can grow.
These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve performance, but it should be done only when the database is first created.
Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can have the same block address if they are in different database files.

8. What is database Trigger?
Ans. A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL.

9. Name two utilities that Oracle provides, which are use for backup and recovery.
Ans. Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. These utilities are Export and Import.
The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file. The Import utility reads the file produced by an export, recreates the definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and recovering the database, all the changes made to the database cannot be recovered since the export was performed. The best you can do is recover the database to the time when the export was last performed.

10. What are stored-procedures? And what are the advantages of using them.
Ans. Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic.

11. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name
Ans. PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during procedure execution. Use of this mechanism enables execution to continue if the error is not severe enough to cause procedure termination.
The exception handler must be defined within a subprogram specification. Errors cause the program to raise an exception with a transfer of control to the exception-handler block. After the exception handler executes, control returns to the block in which the handler was defined. If there are no more executable statements in the block, control returns to the caller.
User-Defined Exceptions
PL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. User accomplishes this by naming an exception as in the following example:
ot_failure EXCEPTION;
In this case, the exception name is ot_failure. Code associated with this handler is written in the EXCEPTION specification area as follows:
EXCEPTION
when OT_FAILURE then
out_status_code := g_out_status_code;
out_msg := g_out_msg;
The following is an example of a subprogram exception:
EXCEPTION
when NO_DATA_FOUND then
g_out_status_code := 'FAIL';
RAISE ot_failure;
Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler. This technique of raising the exception is used to invoke all user-defined exceptions.
System-Defined Exceptions
Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a system-defined exception. Table below gives a complete list of internal exceptions.

PL/SQL internal exceptions.

Exception Name
Oracle Error
CURSOR_ALREADY_OPEN ORA-06511
DUP_VAL_ON_INDEX ORA-00001
INVALID_CURSOR ORA-01001
INVALID_NUMBER ORA-01722
LOGIN_DENIED ORA-01017
NO_DATA_FOUND ORA-01403
NOT_LOGGED_ON ORA-01012
PROGRAM_ERROR ORA-06501
STORAGE_ERROR ORA-06500
TIMEOUT_ON_RESOURCE ORA-00051
TOO_MANY_ROWS ORA-01422
TRANSACTION_BACKED_OUT ORA-00061
VALUE_ERROR ORA-06502
ZERO_DIVIDE ORA-01476

In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not been established.

12. Does PL/SQL support "overloading"? Explain
Ans. The concept of overloading in PL/SQL relates to the idea that you can define procedures and functions with the same name. PL/SQL does not look only at the referenced name, however, to resolve a procedure or function call. The count and data types of formal parameters are also considered.
PL/SQL also attempts to resolve any procedure or function calls in locally defined packages before looking at globally defined packages or internal functions. To further ensure calling the proper procedure, you can use the dot notation. Prefacing a procedure or function name with the package name fully qualifies any procedure or function reference.

13. Tables derived from the ERD
a) Are totally unnormalised
b) Are always in 1NF
c) Can be further denormalised
d) May have multi-valued attributes

(b) Are always in 1NF

14. Spurious tuples may occur due to
i. Bad normalization
ii. Theta joins
iii. Updating tables from join
a) i & ii b) ii & iii
c) i & iii d) ii & iii

(a) i & iii because theta joins are joins made on keys that are not primary keys.

15. A B C is a set of attributes. The functional dependency is as follows
Ans. AB -> B
AC -> C
C -> B
a) is in 1NF
b) is in 2NF
c) is in 3NF
d) is in BCNF

(a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD given, where neither C is a Key nor B is a prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF. Thus the given FDs is in 1NF.

16. In mapping of ERD to DFD
Ans. a) entities in ERD should correspond to an existing entity/store in DFD
b) entity in DFD is converted to attributes of an entity in ERD
c) relations in ERD has 1 to 1 correspondence to processes in DFD
d) relationships in ERD has 1 to 1 correspondence to flows in DFD

(a) entities in ERD should correspond to an existing entity/store in DFD

17. A dominant entity is the entity
Ans. a) on the N side in a 1 : N relationship
b) on the 1 side in a 1 : N relationship
c) on either side in a 1 : 1 relationship
d) nothing to do with 1 : 1 or 1 : N relationship

(b) on the 1 side in a 1 : N relationship

18. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By
Ans. CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMER
The above is
a) Not an error
b) Error - the string in single quotes 'NORTH' and 'SOUTH'
c) Error - the string should be in double quotes
d) Error - ORDER BY clause

(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS

19. What is Storage Manager?
Ans. It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system.
20. What is Buffer Manager?
Ans. It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory.

21. What is Transaction Manager?
Ans. It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting.

22. What is File Manager?
Ans. It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk.

23. What is Authorization and Integrity manager?
Ans. It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data.
24. What are stand-alone procedures?
Ans. Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution.

25. What are cursors give different types of cursors.
Ans. PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors
? Implicit
? Explicit

26. What is cold backup and hot backup (in case of Oracle)?
Ans. ? Cold Backup:
It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy.
If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.
? Hot Backup:
Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.
So different means of backing up database must be used — the hot backup. Issue a SQL command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to backed up. The users can continue to make full use of the files, including making changes to the data. Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to copy those files to the desired backup destination.
The database must be running in ARCHIVELOG mode for the hot backup option.
If a data loss failure does occur, the lost database files can be restored using the hot backup and the online and offline redo logs created since the backup was done. The database is restored to the most consistent state without any loss of committed transactions.

27. What are Armstrong rules? How do we say that they are complete and/or sound
Ans. The well-known inference rules for FDs
? Reflexive rule :
If Y is subset or equal to X then X Y.
? Augmentation rule:
If X Y then XZ YZ.
? Transitive rule:
If {X Y, Y Z} then X Z.
? Decomposition rule :
If X YZ then X Y.
? Union or Additive rule:
If {X Y, X Z} then X YZ.
? Pseudo Transitive rule :
If {X Y, WY Z} then WX Z.
Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of FDs satisfy these three. They are called complete because using these three rules we can generate the rest all inference rules.

28. How can you find the minimal key of relational schema?
Ans. Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency.
Algo. I Determining X+, closure for X, given set of FDs F
1. Set X+ = X
2. Set Old X+ = X+
3. For each FD Y Z in F and if Y belongs to X+ then add Z to X+
4. Repeat steps 2 and 3 until Old X+ = X+

Algo.II Determining minimal K for relation schema R, given set of FDs F
1. Set K to R that is make K a set of all attributes in R
2. For each attribute A in K
a. Compute (K – A)+ with respect to F
b. If (K – A)+ = R then set K = (K – A)+


29. What do you understand by dependency preservation?
Ans. Given a relation R and a set of FDs F, dependency preservation states that the closure of the union of the projection of F on each decomposed relation Ri is equal to the closure of F. i.e.,
((?R1(F)) U … U (?Rn(F)))+ = F+
if decomposition is not dependency preserving, then some dependency is lost in the decomposition.
30. What is meant by Proactive, Retroactive and Simultaneous Update.
Ans. Proactive Update:
The updates that are applied to database before it becomes effective in real world .
Retroactive Update:
The updates that are applied to database after it becomes effective in real world .
Simulatneous Update:
The updates that are applied to database at the same time when it becomes effective in real world .