Sunday, July 4, 2010

C++ interview Questions

What is C++?

Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory management and adding several features - including a new datatype known as a class (you will learn more about these later) - to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.

C++ used for:

C++ is a powerful general-purpose programming language. It can be used to create small programs or large applications. It can be used to make CGI scripts or console-only DOS programs. C++ allows you to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++.

How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

What is the difference between realloc() and free()?

The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

What is function overloading and operator overloading?

Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.
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).

What is the difference between declaration and definition?

The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *; cout <<>

What are the advantages of inheritance?

It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.

How do you write a function that can reverse a linked-list?

void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;

for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}

curnext->next = cur;
}
}




What do you mean by inline function?
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

Write a program that ask for user input from 5 to 9 then calculate the average
#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; i> numb;
while ( numb<5>9) {
cout << "Invalid input, please re-enter: "; cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " <<>}

Write a short code using C++ to print out all odd number from 1 to 100 using a for loop
for( unsigned int i = 1; i < = 100; i++ ) if( i & 0x00000001 ) cout <<>

What is public, protected, private?
Public, protected and private are three access specifier in C++.
Public data members and member functions are accessible outside the class.
Protected data members and member functions are only available to derived classes.
Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes.
Write a function that swaps the values of two integers, using int* as the argument type.
void swap(int* a, int*b) {
int t;
t = *a;
*a = *b;
*b = t;
}

Tell how to check whether a linked list is circular.
Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}

OK, why does this work?
If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.

What is virtual constructors/destructors?
Answer1
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 though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

Answer2
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 though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. Does c++ support multilevel and multiple inheritance?
Yes.

What are the advantages of inheritance?
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.

What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”; cout<


What is the difference between an ARRAY and a LIST?
Answer1
Array is collection of homogeneous elements.
List is collection of heterogeneous elements.

For Array memory allocated is static and continuous.
For List memory allocated is dynamic and Random.

Array: User need not have to keep in track of next memory allocation.
List: User has to keep in Track of next location where memory is allocated.

Answer2
Array uses direct access of stored members, list uses sequencial access for members.

//With Array you have direct access to memory position 5
Object x = a[5]; // x takes directly a reference to 5th element of array

//With the list you have to cross all previous nodes in order to get the 5th node:
list mylist;
list::iterator it;

for( it = list.begin() ; it != list.end() ; it++ )
{
if( i==5)
{
x = *it;
break;
}
i++;
}

Does c++ support multilevel and multiple inheritance?
Yes.

What is a template?
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:


template function_declaration; template function_declaration;
The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

Define a constructor - What it is and how it might be called (2 methods).
Answer1
constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized.

Ways of calling constructor:
1) Implicitly: automatically by complier when an object is created.
2) Calling the constructors explicitly is possible, but it makes the code unverifiable.

Answer2
class Point2D{
int x; int y;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};

main(){

Point2D MyPoint; // Implicit Constructor call. In order to allocate memory on stack, the default constructor is implicitly called.

Point2D * pPoint = new Point2D(); // Explicit Constructor call. In order to allocate memory on HEAP we call the default constructor.

You have two pairs: new() and delete() and another pair : alloc() and free().
Explain differences between eg. new() and malloc()

Answer1
1.) “new and delete” are preprocessors while “malloc() and free()” are functions. [we dont use brackets will calling new or delete].
2.) no need of allocate the memory while using “new” but in “malloc()” we have to use “sizeof()”.
3.) “new” will initlize the new memory to 0 but “malloc()” gives random value in the new alloted memory location [better to use calloc()]

Answer2
new() allocates continous space for the object instace
malloc() allocates distributed space.
new() is castless, meaning that allocates memory for this specific type,
malloc(), calloc() allocate space for void * that is cated to the specific class type pointer.

What is the difference between class and structure?
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public.
Class: Class is a successor of Structure. By default all the members inside the class are private.


What is RTTI?
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many Interview Questions - Homegrown versions with a solid, consistent approach.

What is encapsulation?
Packaging an object’s variables within its methods is called encapsulation.

Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE

Answer1
POLYMORPHISM : A phenomenon which enables an object to react differently to the same function call.
in C++ it is attained by using a keyword virtual

Example
public class SHAPE
{
public virtual void SHAPE::DRAW()=0;
}
Note here the function DRAW() is pure virtual which means the sub classes must implement the DRAW() method and SHAPE cannot be instatiated

public class CIRCLE::public SHAPE
{
public void CIRCLE::DRAW()
{
// TODO drawing circle
}
}
public class SQUARE::public SHAPE
{
public void SQUARE::DRAW()
{
// TODO drawing square
}
}
now from the user class the calls would be like
globally
SHAPE *newShape;

When user action is to draw
public void MENU::OnClickDrawCircle(){
newShape = new CIRCLE();
}

public void MENU::OnClickDrawCircle(){
newShape = new SQUARE();

}

the when user actually draws
public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}


Answer2
class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};

class CIRCLE{
public int r;
public virtual Draw() { this->drawCircle(0,0,r); }
};

class SQURE
public int a;
public virtual Draw() { this->drawRectangular(0,0,a,a); }
};

Each object is driven down from SHAPE implementing Draw() function in its own way.

What is an object?
Object is a software bundle of variables and related methods. Objects have state and behavior.

How can you tell what shell you are running on UNIX system?
You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

What do you mean by inheritance?
Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

Difference between Struct and Class in C++?

The only difference is the default visibility of members (both support data and functions and constructors and destructors).- classes have private members by default- structs have public members by default
Either type of object can be created on the stack (transient automatic variable) or on the heap (allocated via the “new” operator and expressly deleted using the “delete” operator). There is no difference in the way the class or struct lays out in memory.
I personally consider it bad form to use default visibility so I don’t do that. So in my case case there is no difference at all.
Some programmers use struct to indicate that the object is simple data. They will add constructors, accessors, assignment operators etcetera for protection. They will also add serialization an deserialization functions if the data is displayed or written to a file.
The same programmers will always use class when the object does something other than just hold data. For example, a class may represent a screen object or an external device, or a database access object. In these cases, the data is at least partly a configuration of the object.
In short, the struct keyword is superfluous and leads to confusion. There is no C++ language-specific reason to use it. It was probably retained to ensure compatibility with older C code




58 comments:

  1. Thanks man
    Looks like i covered basics.

    ReplyDelete
  2. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Embedded Training in Chennai

    ReplyDelete
  3. Hello There,

    Great post. Well though out. This piece reminds me when I was starting out C++ interview Questions after graduating from college.

    When i run "my programs" then the black window appear.i mean "my programs" for programs i have created in my pc.
    How can i compile or what should i include in my source...or anything else,to run my programs in silent mode,mean to don't appear the black window and to not appear anything in the taskbar.
    Is that possible?
    I read multiple articles and watched many videos about how to use this tool - and was still confused! Your instructions were easy to understand and made the process simple.

    Cheers,
    Preethi

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Hello There,

    A really interesting, clear and easily readable Embedded Systems article of interesting and different perspectives.I will clap. So much is so well covered here.



    I know this question has been answered numerous time, but I can't seem to find a right Linux OS for it.
    I have this dinosaur laptop that I got from my aunt, and she was using it for engineering but decide to give it to me. Now that I have this laptop and check it's spec.
    It was this one.
    Awesome! Thanks for putting this all in one place. Very useful!


    Cheers,
    Radhey

    ReplyDelete
  6. This information you provided in the blog that is really unique I love it!! Thanks for sharing such a great blog Keep posting..
    Embedded Systems course in Delhi

    ReplyDelete
  7. I am really very happy to find this particular site. I just wanted to say thank you for this huge read!! I absolutely enjoying every petite bit of it and I have you bookmarked to test out new substance you post.
    Click here:
    angularjs training in bangalore
    Click here:
    angularjs training in pune

    ReplyDelete
  8. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    Blueprism online training

    Blue Prism Training in Pune

    Blueprism training in tambaram

    ReplyDelete
  9. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Devops Training in Chennai

    Devops Training in Bangalore

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. This information you provided in the blog that is really unique I love it!! Thanks for sharing such a great blog Keep posting..
    Best Training and Real Time Support

    Sap Abap Training From India

    Sap Pp Training From India

    ReplyDelete
  12. I really appreciate for your brilliant Efforts on spending time to post this information in a simple and systematic manner, so That visitors and readers can easily Understand the concept.I Efforts must appreciate you posting these on information.
    SCCM Self Placed Videos

    Office 365 Self Placed Videos

    Exchange Server Self Placed Videos

    ReplyDelete
  13. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    DataScience Training institute

    DataStage Training institute

    Dell boomi Training institute

    ReplyDelete
  14. I simply want to give you a huge thumbs up for the great info you have got here on this post.

    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  15. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.
    Data Science training in rajaji nagar | Data Science with Python training in chenni
    Data Science training in electronic city | Data Science training in USA
    Data science training in pune | Data science training in kalyan nagar

    ReplyDelete
  16. Awesome! Education is the extreme motivation that open the new doors of data and material. So we always need to study around the things and the new part of educations with that we are not mindful.

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in chennai

    ReplyDelete
  17. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    https://www.blogger.com/comment.g?blogID=3525722108480594643&postID=6424502006370903250&page=1&token=1551258222376

    ReplyDelete
  18. I think you have a long story to share and i am glad after long time finally you cam and shared your experience.
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete
  19. Pleasant Tips..Thanks for Sharing….We keep up hands on approach at work and in the workplace, keeping our business pragmatic, which recommends we can help you with your tree clearing and pruning in an invaluable and fit way.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  20. Thanks For Sharing The Information The information shared Is Very Valuable Please Keep Updating Us Time just went On reading The article Python Online Training Aws Online Training Hadoop Online Training Data Science Online Training

    ReplyDelete
  21. For such type of information, be always in touch with us through our blogs. To find the reliable method to obtain assist to create customer checklist in QB desktop, QuickBooks Payroll Support Phone Number service might help you better.

    ReplyDelete
  22. If you don't, this could be basically the right time so you can get the QuickBooks Enterprise Support

    ReplyDelete
  23. QuickBooks Support Number For Business All of the above has a particular use. People working with accounts, transaction, banking transaction need our service. Some people are employing excel sheets for a few calculations

    ReplyDelete
  24. QuickBooks Enterprise Techical Support Number contact number team can help you deal with most of the issues of QB Enterprise. Now let’s have a look on the industry versions therefore it has furnished us with. You will discover six forms of industry versions that QB Enterprise offers.

    ReplyDelete
  25. Updates constantly come with fixes, patches, and bugs. If you are experiencing virtually any issues into the installing of the latest QuickBooks updates? Then easily contact our QuickBooks Helpline Number.

    ReplyDelete
  26. Only you must do is make an individual call at our toll-free QuickBooks Payroll tech support number . You could get resolve all of the major issues include installations problem, data access issue, printing related issue, software setup, server not responding error etc with our QuickBooks Online Payroll Contact Number.

    ReplyDelete
  27. Yes, our QuickBooks Enterprise Technical Support Number may be a magic bullet to solve any QuickBooks Enterprise tech issue. Our QuickBooks Enterprise Support team comes with QuickBooks Experts who can solve your problems instantly as soon as they get a call on QuickBooks Enterprise number.

    ReplyDelete
  28. You named a blunder and then we have the solution, this could be essentially the most luring features of QuickBooks Enterprise Support Number channel available on a call at .You can easily avail our other beneficial technical support services easily as we are simply an individual call not even close to you.

    ReplyDelete
  29. Plus in the upcoming 2019 type of excellent Plus in the upcoming 2019 type of excellent QuickBooks accounting software, you will see plenty of developments and improvements, especially provisioned to just improve the user experience. accounting software, you will see plenty of developments and improvements, especially provisioned to just improve the user experience.

    ReplyDelete
  30. Our hard-working QuickBooks Tech Support Number team that contributes into the over all functioning of your business by fixing the errors that could pop up in QuickBooks Payroll saves you against stepping into any issue further.

    ReplyDelete
  31. QuickBooks Support Phone Number now have a technique of deleting the ability which you have put immediately from our storage. Thus, there isn't any probability of data getting violated. You should arrive at us in terms of a number of software issues.

    ReplyDelete
  32. Primeaxle always provides you with the best and most amazing team to simply resolve or fix your errors or issues whenever you want. And also we have the best account specialists in all of us. And they're always working round the clock to just beat your expectations. Our Quickbooks Support Number is obviously free and active to present you the best QuickBooks customer support because of its great products. So always get-in-touch with your QuickBooks customer care team for fast and simple help and get more knowledge or information regarding the QuickBooks.

    ReplyDelete
  33. Will not need to worry if you should be stuck with QuickBooks issue in midnight as our technical specialists at QuickBooks Tech Support Number is present twenty-four hours just about every day to serve you combined with best optimal solution very quickly.

    ReplyDelete
  34. Every user will get 24/7 support services with this online technical experts using QuickBooks Help & Support. When you’re stuck in times for which you can’t discover a way to get rid of a concern, all that's necessary would be to dial QuickBooks customer support contact number. Be patient; they will certainly inevitably and instantly solve your queries.

    ReplyDelete
  35. At QuickBooks Tech Support Phone Number, you'll find solution each and every issue that bothers your projects and creates hindrance in running your organization smoothly. Our team is oftentimes willing to permit you to while using the best support services you could possibly ever experience.

    ReplyDelete
  36. Since it is accounting software, every so often you have a query and will seek assistance. This is why why QuickBooks has opened toll free QuicKbooks Customer Support Number. For telephone assistance just call or email to support team. You are able to fetch quick resolutions for the issues you face along with your QuickBooks.

    ReplyDelete
  37. QuickBooks Help & Support is accounting software, which is a cloud-based application produced by Inuit Inc. In fact, the application has been developed with the intention of keeping a safe record of financial needs for the business. Additionally, it is a user-friendly accounting software; an easy task to maintain; assisting the company in keeping the records of financial transactions, and a whole lot more features.

    ReplyDelete
  38. Intuit is perhaps all concerning User expertise which explains why they need creating dedicated QuickBooks Support Phone Number variety; Users will dial the fee number just in case they usually have any facilitate in regards to the code.

    ReplyDelete
  39. QuickBooks Enterprise Support Phone Number assists anyone to overcome all bugs from the enterprise types of the applying form. Enterprise support team members remain available 24×7 your can buy facility of best services.

    ReplyDelete
  40. QuickBooks accounting software is the most effective accounting software commonly abbreviated by the name QB used to manage and organize all finance-related information properly. Reliability, accuracy, and certainly increase its demand among businessmen and QuickBooks Support Phone Number.

    ReplyDelete
  41. QuickBooks Payroll Technical Support Number is available in involving the Basic & Advanced form of QuickBooks Payroll Support contact number 1-888-986-7735. It showers slightly more advantages to the user, in comparison with the Basic Payroll Version.

    ReplyDelete
  42. QuickBooks Support Phone Number has developed the software with almost evolution to manage all checks and taxes issues. Since no body is well in this globalization. More often than not when people are protesting about incorrect calculation and defaults paychecks results.

    ReplyDelete

  43. So when QuickBooks Support Phone Number know that QuickBooks has many great features and QuickBooks scan manager is amongst the amazing attributes of QuickBooks just to maintain your all documents. However, if you are not using this unique and a lot of helpful QuickBooks accounting software, then you're definitely ignoring your business success.

    ReplyDelete
  44. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful .Dell Boomi Training in Bangalore

    ReplyDelete
  45. Thanks for sharing the information...
    AngularJS Training in Bangalore | AngularJS Course Fees | AngularJS 6 - i Digital Academy
    - AngularJS Training in Bangalore - Learn AngularJS 6 from Expert Real-time Trainers at i Digital Academy with Live Projects and Placement Assistance. Book a Free Demo Today.

    ReplyDelete
  46. Improper deletion of files in this Software, incomplete installation or uninstallation of an application for the Software, etc can result in system file errors. If you would like to learn How To Fix Quickbooks Error 9999, you can continue reading this blog.

    ReplyDelete
  47. I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.
    AWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery


    ReplyDelete
  48. It is amazing and wonderful to visit your site. Thanks for sharing information; this is useful to us....

    MERN Stack Training in Delhi

    ReplyDelete