Tag Archives: interview questions

C++ interview questions on strings with string reversal and tough manipulation

C++ interview questions on strings with string reversal and tough manipulation

Dseadlock
what is deadlock? how to detect if a deadlock has occurred and how to troubleshoot?

String:
Difference between C-strings and string class in C++.
C++ strings are less efficient, but they have more encapsulated functionality. C strings are manipulated by standard functions while C++ string is object-oriented and string is a class. C string is simply an array of characters.
C++ string is a class n hence ny declaration such as string str is declaration of an object str of string class. Thus in built methods add functionality. on the other hand C strings are mere char pointers.
agreed! both answers are correct…good …
string class is a wrapper over c Strings(char arrays)

Given char* func1(char* target, char* substring,char* replacement)
write a c++ code to find the substring in the target and replace the whole substring with the replacement. (hint: replacement can be larger or smaller than the substring.)consider all possible test cases and check.

1) find the starting index of substring
a) can be done by KMP in O(n)
b) brute force O(n*m)

2) replacing
a) if the word to be replaced is larger– then first replace the characters till the length of substring..then use shifting so–> O((l1-l2)*n)
b) if the word to be replaced is small
then just replace snd shift

Can we use extra array for dealing this question?

I think we can just assume the target array have enough memory after ‘\0’
because every replace string work like that or make error

kmp= KMP.c: Implements strstr library function using the Knuth-Morris-Pratt
substring search algorithm.

I made some but it is not KMP or something efficient algorithm but it is easy to write front of interviewer.

int main(int argc, char *argv[])
{

int idx = 0;
char target[100];
char *pTag = target;
char sub[10];
char replace[100];
char *pRpr = replace;
if(argc != 4)
{
cout << "Exit... Bye Bye\n"; exit(1); } strcpy(target, argv[1]); strcpy(sub,argv[2]); strcpy(replace,argv[3]); //Loop until target 0 char * pTg, * pSb, *pRp; pRp = replace; while(pTag != '\0') { pTg = pTag; pSb = sub; while(*pSb != '\0' && *pTg != '\0' && *pTg++ == *pSb++); if(*pSb == '\0' && *(pTg -1) == *(pSb -1)) { while(*pRp != '\0')pRp++; while((*pRp++ = *pTg++) != '\0'); while((*pTag++ = *pRpr++) != '\0'); cout << target << "\n"; return 0; } pTag++; } } #include
using namespace std;

void replace(char *target, char *substring, char *replace);

int main()
{
char target[100] = “MyNameIsGajanan”;
char *substring = “Gajan”, *rep = “AAA”;
//cout << target < n
j = i-> n
k = j -> n
Cheema on December 26, 2009 |Edit | Edit

Oops! I meant O(n^2)
Loop structure will just be nested loops

i = 0 -> n
j = i-> n

Reply to Comment
particularraj on November 12, 2009 |Edit | Edit

My cents:

Building suffix trees is not a bad idea. We can get that in O(nlogn) time.
Reply to Comment
Vishal on November 15, 2009 |Edit | Edit

Take a string

1. Reverse the string
2. XOR with the Original String
3. Find the longest sequence of 0s in the XORed result which will be the corresponding answer

Hi Vishal,

You solution will not work always… You can try it on RACECAR……..
reverse of RACECAR is RACECAR only …. so xoring dem wud giv 0000000 …. which is the longest palindrome … i think vishal’s solution will work for all cases …
Anonymous on November 28, 2009 |Edit | Edit

reverse of RACECAR is RACECAR only …. so xoring dem wud giv 0000000 …. which is the longest palindrome … i think vishal’s solution will work for all cases …
whoami on December 14, 2009 |Edit | Edit

that is an awesome approach.. guess it will work for all cases…
small patch: if XORing is tough for charecters while coding… we can just subtract both the strings charecter by charecter… and then count the max no of consecutive zeros….
Anonymous on January 05, 2010 |Edit | Edit

This won’t work for HTTKNOM
fgh on January 05, 2010 |Edit | Edit

this won’t work for HTTKNOM
Anonymous on January 07, 2010 |Edit | Edit

Stupid solution.

APQP
PQPA

XOR, none are zeroes, but PQP is the longest palindrome.
Reply to Comment
parry on November 15, 2009 |Edit | Edit

start with the first character. try to lookup the same character from the bak. on finding the same character from the back check if the substring is palindrome or not. keep on finding the same character until u reach the index of the first character.

keep on doing the same for all the characters. ….O(n^2)
Anonymous on November 16, 2009 |Edit | Edit

If i’m not mistaken would’nt this be O(n^3)
Reply to Comment
Anonymous on November 16, 2009 |Edit | Edit

Just reverse the string and find the largest substring in both the strings. O(n^2).
Reply to Comment
trey on November 16, 2009 |Edit | Edit

finding the longest substring of the string and it’s reverse won’t work. Consider
abcdefgHELLOWORLDgfedcba The longest palindrome is actually LL, that method would return abcdefggfedcba
Dan on December 15, 2009 |Edit | Edit

the longest palindrome is infact OWO !!
Reply to Comment
gagdeep on November 17, 2009 |Edit | Edit

Keep a current pointer on the second element a(1). place two other pointers at current-1 and current+1. check if curr-1 and curr+1 are equal. then move current pointer ahead. again set curr-1 and curr1 and check for:
If curr is at ith position:
while(i>0)
{
if (curr-1 == curr+1)
{
(curr+1)++;
(curr-1)–;
i–;
}
else break;
}

keep tack of the largest one by storing the value of current for which the length of palindrome was max. also keep track of it’s length for each i. Then u can print the longest palindrome.
gagdeep on November 17, 2009 |Edit | Edit

It’s complexity will be O(n). I have a working code for this. if anybody want.
Anonymous on November 17, 2009 |Edit | Edit

test case: abcddcbe

does it work?
gagdeep on November 17, 2009 |Edit | Edit

No, It doesnot… because i assumed that palindrome will be of odd length…

For this case… place a current ptr and move the curr+ ptr till it goes to the value which is not equal to the current ptr. and then follow the steps above.
Reply to Comment
bala on November 20, 2009 |Edit | Edit

@gagdeep what does the ‘i’ signify ??
Reply to Comment
nalin on November 20, 2009 |Edit | Edit

Can you show the working code by which you arrived O(n)
Reply to Comment
kunalgaind on November 20, 2009 |Edit | Edit

I think we cannot solve this question in less than O(n^3) complexity……..as ideally there are n*n different string that can be created using a string of length n……For example there are 1 string of length n that can be formed from given string and there are 2 string of length n-1 that can be formed using a string of lenght n-1 and there are n string of length 1.

So if you sum it all, there are 1+2+ ……..+ n-1 + n strings = O(n*n)……..

We know how to check for one string in O(n) time, so I think we can just repeat the loop by checking string of length n to 1 and stop whenever we find any palindrome…..

Seriously, I don’t think we can solve this question in less than this time, because we have to check for string of each length and in worst case there might not be any palindrome in string and so we might end up with generating palindrome on length 1 i.e . character itself, if you consider that to be a palindrome…..

Please share your thoughts, I would be happy to hear from anyone….who can help me in improve on this solution………..
Reply to Comment
Thiyanesh on November 20, 2009 |Edit | Edit

maxindex = 1;
maxlen = 1;
for(index = 1 to str.length) {
for(cur = 1 to min(index, abs(str.length – index))) {
if(str[index + cur] == str[index – cur]) {
if(cur < maxlen) continue; maxlen = cur; maxindex = index; } } } May fail for the boundary conditions. But this the logic which i can think of for O(n2) complexity. We need two such code blocks one for even length and one for the odd length. Hence the time complexity is O(n2). O(1) space complexity Reply to Comment kunalgaind on November 20, 2009 |Edit | Edit I am not sure about suffix tree, as I have not read those yet, but I don't think we can solve this question iteratively in less than O(n^3) and I don't think dynamic programming will work too as we cannot use the result that I got in previous iteration because if I have two strings that are palindrome then I cannot say that if I merge both string then those will be palindrome also... Here is my solution using O(n^3) complexity. There are n*n different string that can be created using a string of length n......For example there are 1 string of length n that can be formed from given string and there are 2 string of length n-1 that can be formed using a string of lenght n-1 and there are n string of length 1. So if you sum it all, there are 1+2+ ........+ n-1 + n strings = O(n*n)........ We know how to check for one string in O(n) time, so I think we can just repeat the loop by checking string of length n to 1 and stop whenever we find any palindrome..... Seriously, I don't think we can solve this question in less than this time, because we have to check for string of each length and in worst case there might not be any palindrome in string and so we might end up with generating palindrome on length 1 i.e . character itself, if you consider that to be a palindrome..... Please share your thoughts, I would be happy to hear from anyone....who can help me in improve on this solution........... Reply to Comment kcoder on November 21, 2009 |Edit | Edit A working solution. O(n*n*n) complexity but good for an interview. bool ispalindrome (const char * start, const char * end) { while (start < end) { if (*start != *end) { return false; } start++; end--; } return true; } char * longestPalindrome(const char * str_p) { int len = strlen (str_p); const char * startOfPal = 0; // start of palindrome. const char * endOfPal = 0; // end of palindrome. int maxLenOfPal = 0; // len of palindrome. for (int i = 0; i < len; i++) { for (int j = len-1; j > i; j–)
{
const char * start = str_p + i;
const char * end = str_p + j;

if (ispalindrome(start, end))
{
if ((end – start + 1) > maxLenOfPal)
{
startOfPal = start;
endOfPal = end;
maxLenOfPal = end – start + 1;
}
}
}
}

Reply to Comment
Anonymous on November 21, 2009 |Edit | Edit

Not sure what happened to the white space.

Here is a quick test I used.

const char * str = “testanaradaring”;
char * x = longestPalindrome(str);

if (x)
{
cout << x << endl; } else { cout << "No palindrome found." << endl; } Anonymous on November 23, 2009 |Edit | Edit the simplest way is O(N^2) if applying suffix tree time can be reduced to O(NlogN) asuran on November 23, 2009 |Edit | Edit the simplest way is O(N^2) if applying suffix tree time can be reduced to O(NlogN) Reply to Comment bewnet on November 22, 2009 |Edit | Edit How about this way: 1. define stringbulder variable called sb and an int called numberOfChars and max 2. for each character in the string 3. add the character to sb, and set numberOfChars to 1. 4. for each remaining character in the string 5. append the character to sb and increment numberOfChars by 1. 6. if the character is the same as the character read in step 2, then what we have in sb is a potential palindrom so, call a helper funtion called IsPalindrome with the value in sb as an argument. 7. If step 6 returns true, then add the content of sb to a dictionary with sb as a key and numberOfChars as a value---you can have duplicate checks 8. inner loop ends here 9. if numberOfChars > max then reset max to numberOfChars and clear sb
9. loop to the first loop.
10. Now, all possible palindrome strings are in your dictionary. Return a key with value equal to max.

Note that:
The algorithm generates all possible palindroms but, i think there might be a better way of doing it.

Reply to Comment
anon on November 25, 2009 |Edit | Edit

Longest thread of answers to Longest palindrome finding 🙂
Reply to Comment
SK on December 23, 2009 |Edit | Edit

could not post the link. google for this. the first link has a good solution

finding-the-longest-palindromic-substring-in-linear-time.
Reply to Comment
Anonymous on January 07, 2010 |Edit | Edit

It’s awesome to see people using suffix tree and O(nlogn) at the same time !!
Anonymous on January 07, 2010 |Edit | Edit

And why not?

There are simpler implementations of suffix tree which are O(nlogn).

Because implementing suffix tree can be so complex, ppl might choose to lose some run time over the possible maintenance headaches.
Reply to Comment
c on February 03, 2010 |Edit | Edit

My suggestion is that any approach of O(n^2) time and O(1) space that can be well explained and you can write working code during an interview would suffice!
Reply to Comment
Ryan on February 25, 2010 |Edit | Edit

This self-contained C program will print out all of the palindrome lengths for all possible centers, and it will do it in O(n) time. It is a port of the algorithm in Haskell authored by Johan Jeuring here: johanjeuring.blogspot.com/2007/08/finding-palindromes.html

#include
#include
#include

// Simple linked list functions
typedef struct Node Node;
struct Node {
int len;
Node* next;
};

Node* insertNode(Node* head, Node* node) {
node->next = head->next;
head->next = node;
return node;
}

Node* createNode(int len) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->len = len;
return newNode;
}

Node* insertNum(Node* head, int len) {
return insertNode(head, createNode(len));
}

void printReverse(Node* node) {
if (node != NULL) {
printReverse(node->next);
printf(“%d “, node->len);
}
}

void printReverseList(Node* head) {
printReverse(head->next);
printf(“\n”);
}

void cleanList(Node* head) {
Node* curr = head;
while (curr != NULL) {
Node* next = curr->next;
free(curr);
curr = next;
}
}

int main(int argc, char* argv[]) {
if (argc < 2) { printf("USAGE: ./pal string\n"); return 0; } char* a = argv[1]; int n = 0; int len = strlen(a); int currTail = 0; // length of the longest tail palindrome Node* centers = createNode(0); centers->next = NULL;
while (n < len) { if (n - currTail != 0 && a[n - currTail - 1] == a[n]) { n++; currTail += 2; continue; } Node* center = centers->next;
insertNum(centers, currTail);
int centerDist = currTail;
while (centerDist != 0 && center != NULL && centerDist – 1 != center->len) {
centerDist–;
insertNum(centers, center->len > centerDist ? centerDist : center->len);
center = center->next;
}
if (centerDist == 0) {
n++;
currTail = 1;
} else {
currTail = center->len;
}
}
Node* center = centers->next;
insertNum(centers, currTail);
while (currTail != 0) {
currTail–;
insertNum(centers, center->len > currTail ? currTail : center->len);
center = center->next;
}
printReverseList(centers);
cleanList(centers);
return 0;
}

Reply to Comment
Anonymous on March 08, 2010 |Edit | Edit

Reverse the string and find biggest substring.
hary on March 08, 2010 |Edit | Edit

Precisely. One moethod is what anonymous quoted. reverse and find the longest common substring. O(n2) method.

Second could be for every possible position in the string find the palindrome and keep track of the max found so far. One also has to take care of odd length and even length strings.
AGain O(n2) method.

Reply to Comment
Anonymous on March 08, 2010 |Edit | Edit

No need for such complex algorithms !!!

I was asked this question, I proposed trying all combination (O(n^2) I think) he looked convinced with that approach.
Reply to Comment
Tarun Phaugat on March 09, 2010 |Edit | Edit

Example:
================
Str1=abcbabcmoms

Str2=abcba

ALGO:
================
1.a take A[i]==A[j] , decrement J– till i
if A[i]==A[j]
take paldromeindex=i
and increment i and decrement j till i=j
RANGE[k]=J-I

1.b sort range and return the longest one

CODE:
================

private string LongestPalindrom(Str S1,int size)
{
int maxrange =0;

For(int i=0;i0;J–)
{
char ch2=s1[j];

IF(CH1==CH2 && i!=j)
{
int range= j-i;
i++;
ch1=s1[i];
}
}

IF(MAXRANGE= pali; j–){
tempRange = j – *begin;
if(str[pali] == str[j]){
pali++;
}else{
tempRange = 0;
if(pali != *begin){
break;
}
}
}
if(*range < tempRange){ *range = tempRange; } } } Reply to Comment O(n^2) on April 11, 2010 |Edit | Edit int main() { char a[]="abcdaeeadabb"; char *p,*q,*r,*found; int i=0; int max=0; for(p=a;*p!='\0';p++) { q=p; r=a+strlen(a); while(qmax) {max=i; found=p;}
}
if(q==r) max=max+1;
std::cout<=0) && (end <= n)) { if((maxEnd - maxStart) < (end-start)) { maxEnd = end; maxStart = start; } end++; start--; } start++; end++; } for(int i = maxStart; i <= maxEnd; i++) printf("%c", str[i]); } implement atoi() // to-do: 1.take the first char in str for signed/unsigned check // 2.check for invalid char in str int my_atoi(const char *str) { int i=0; while ( *str ) { i = (i<<3) + (i<<1) + ((*str) - '0'); ++str; } return i; } class A1 { public: int upper; int lower; A1( int i ) : lower( i ), upper( lower+1 ) { }; }; what is wrong with the above code? when i ran the above code with initial value 10, upper gets initialised but not lower. I tried running the same .the lower doesn't get initialised. can somebody explain why? I guess the names of the member variables appearing on the Initialization list should be in the same order as they appear in the class (declaration). There initialization take place in order of there declaration,,, so by that I mean first upper get initialized and after that lower,, So in the previous questions assuming i to be 10 upper = unknow lower value + 1 // lower = 10 on my pc, lower is initialized (equals i) but not upper But I have no idea about why from c++ primer: the initializer only shows which value to set which member, but the order of initializers has no meaning compiler will set upper first, then lower therfore A1( int i ) : upper( lower+1 ) , lower( i ){ }; // lower = 10; upper = 11 Hey Anonymous, there is a small correction. upper will get initialized first. But at that time the value of lower is unknown. So upper value will be = unknown + 1.So we cant predict that it will be 11. Next lower get initialized with i . so its value will be 10 Always remember the initialization order is 1) Super Class (Based on the inheritance order, not mem init list) 2) Memeber (Based on the order they declared in class, not mem init list) 3) Computation inside the constructor Write a function that would have as input a string,and list of characters to be deleted from the string. How would you reverse the output string? Since there is no restriction to use string class function, strtok() can be used. But if not then do (crude method) F(char* iStr, char* List) { int i = strlen(iStr); int j = 0 ; for( k = 0 ; k < strlen(List) ; k++) for( j = 0 ; j < i ; j++) if(iStr[j] == List[k]) { iStr[j] = iStr[j+1]; iStr[j+1] = ' '; j += 1; } } Complexity O(strlen(List) * strlen(iStr)) string removechar(string in, string remove) { int i=0; int asciiarray[256]; string temp; for (i=0; i<256; i++) asciiarray[i] = 0; for (i=0; i

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

c++ interview questions on iterator and arrays

Iterator
3.Question: What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator.
Answer: .An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be “attach” to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.

Array:
Write a function to add an array of numbers.
what kind of numbers, real/integer

int add_Num(int arr[], int n ){

int sum = 0;
int j = 0;
while (j < n ){ sum+=arr[j]; j++; } return sum; } merging two arrays (second one being larger than the elements in it) into one without using 3rd array. what all errors is possible if u write past the array bounds? memory corruption, call stack corruption. In unix, scope is limited to these 2 inside a process. In RTOS, the corruption can span across multiple tasks/processes you inadvertently overwrite some portion of memory that some pointer or a variable is pointing to when you write past array bounds 4.Question: Why are arrays usually processed with for loop? Answer: The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a.length -1. That is exactly what a loop does.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

c++ interview questions on static classes, static initializer, and static members

c++ interview questions on static classes, static initializer, and static members

Static
What is static method? What is a static initializer?

A static method is not bound to an instance of a class. It does not need a class instance to access it. But to access other (non-static) members of the class from the static method, we need to declare a class instance inside static method.

plaese explain in detail with example,how can we acess the member of class without instance????
Static Initializer Block is concept of Java. Do we really have this in C++?
Is it same as Initialization of Static variables.
?
Question didn’t ask about static specific to classes.

We can explain a static method in terms of a class or as a normal non-class function.

A staic method in a class’s role is to use the static data members only.
and staic method can be accessed by a static/non-static class object.
But a static method cannot have non-static access to the data-members.
And static method cnnot be constant, volatile and virtual.

Now, static non-class method: A staic keyword in front of a non-class method is used to limit the method scope to the current compilation unit. It has internal linkage and one can use this principal in C for information hiding, while class’s static method/data-member has external-linkage.
e.g.
In abc.cpp/c
static void print_some_data()
{
}
is limited in abc.cpp/c only, no other compilation unit in an application can use it.

we use static so tht there is no need to acces tht method or data thro an object..
eg. in Java,C# we use..

public static void main(String args[])
{ }

bcoz de prog is started from main, the compiler vil not create an object to access this method and from here the execution begins..

Static members,
What are they?
Their reason of existence?
Challenges they have? (Link initilization)……

Static data members are members are that shared by all instances of a class.
A common usage is to keep account of the numbers of instances of a class.
Static member functions are used to access private static data members, they do not have a this pointer and they can only access static data members, this is because they are not attached to an instance of an object

why use static variables, where are the static variables stored,
it is similar to a brainbench test with 4 possible answers to each question.

1) o/p of a program containing two two static variables with the same name in a program

What is “static” mean in the c++?
Was probably looking for you to mention it’s allocation at the start of the program, one copy in memory, etc.
Static
1. Within a function, there is one copy of the variable that retains its value even when the function returns.
2. Within a class, all objects share the static variable and the static variable is accessed using the class name.
3. In the global scope a static variable is local to the current file.

“Static variables and static functions. Local static variables within a function and their use.”

How do you access the static member of a class?
::

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ Interview questions on name mangling, extern, and struct

C++ Interview questions on name mangling, extern, and struct

Name mangling:
What is name mangling in C++??
The process of encoding the parameter types with the function/method name into a unique name is called name mangling. The inverse process is called demangling.
For example Foo::bar(int, long) const is mangled as `bar__C3Fooil’.
For a constructor, the method name is left out. That is Foo::Foo(int, long) const is mangled as `__C3Fooil’.

What does extern “C” int func(int *, Foo) accomplish?
It will turn off “name mangling” for func so that one can link to code compiled by a C compiler.

Const:
What is the difference between const char *myPointer and char *const myPointer?
Const char *myPointer is a non constant pointer to constant data; while char *const myPointer is a constant pointer to non constant data.
Name two cases where you MUST use initialization list as opposed to assignment in constructors.
Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them.
Global variables:
Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?
C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.

Struct:
What are the differences between a C++ struct and C++ class?
The default member and base class access specifiers are different.
The C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specifier and private base class inheritance.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

c++ interview questions on inline functions and this pointer

Inline:
What are inline functions? How would you reduce the chances of gcc making a function
Make it virtual.
agree, or use function pointer
An inline functions is used to tell the compiler to insert the complete body of the function where ever they are called. A function defined in a class definition is automatically treated as inline.

By specifying command line option -finline-limit=n while compilation.
Simplest way out, if you have a function

typename f(…)

, you do the following declaration:

typename f(…) __attribute__ ((noinline));

If you also want to disable all other possible optimisations, stick the line

asm(“”);

somewhere in the function – compiler thinks it’s got some Assembler to handle, so it will take things easy…

Making the function ‘longer and complicated’ reduces the chances of getting the function inlined.
What is inline function??
The __inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler’s discretion. For example, the compiler does not inline a function if its address is taken or if it is too large to inline.

This pointer:
What happen if i delete “this” in member function ? can you call member functions after doing this ?
destructor of class is called to which this pointer belongs. Memory is freed (or should say marked as free space) to be used by OS for other purposes. I think you can call other function but behavior is undefined because you don’t know when OS will allocate this memory to some other process..

You should be safe as a long as you don’t end up using any member variables. Deleting this does not affect member functions.
Interesting it is called suicide
If the memory for this object was not on the heap then the program will crash
If the client does not come to know the object has been deleted and use the object to call a function or some thing then the program will crash

What is “this” pointer?
The this pointer is a pointer accessible only within the member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.
When a nonstatic member function is called for an object, the address of the object is passed as a hidden argument to the function. For example, the following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object’s address is available from within the member function as the this pointer. It is legal, though unnecessary, to use the this pointer when referring to members of the class.

What happens when you make call “delete this;” ??
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.
You should never do this. Since compiler does not know whether the object was allocated on the stack or on the heap, “delete this” could cause a disaster.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview questions on STL containers like vector and list

C++ interview questions on STL containers like vector and list

Containers:
vector and list difference. complexities of alogrithms.

Vector –
1> Insertion – O(n) /* Resizing the array */
2> Search – O(n) /* Sequential */ , O(logn ) /* Binary */
3> Random Access – Yes .
4> Deletion – O(n) /* Shifting & Resizing */
5> Sequential Memory used .

List –
1> Insertion – O(1)
2> Search – O(n)
3> Deletion – O(n)
4> Random Access – No
5> Linked allocation , hence more memory efficient .
Reply to Comment
Anonymous on April 10, 2010 |Edit | Edit

For list, the complexity of deletion should be O(1).
3> Deletion – O(1)

What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.
how to delete a node in a list
single linked list ? – then save pointer to next node, start from head and go to the node right before the node being deleted, and change it’s “next” pointer to the one you saved.
Now you can delete node.
double linked list ? – no need to start from head, just reassign pointers in neighbor nodes properly to point to each other instead of to the node being deleted, and then delete the node. Of course, special care for first and last nodes, which have some NULL pointers.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

c++ interview questions with overloading and operators that cannot be overloaded

c++ interview questions with overloading

Overloading:
Have you overloaded operator new ? I said yes then Y did u do that ?
Overloading new will help a programmer to allocate memory in his own way, probably in a more optimzed manner. For example jus in case if somebody want to recycle the memory, by not actually deleting the Object instead maintaining a list of deleted object and then want to jus copy the new parameters there , instead of calling the allocate memory function and all.
To implement garbage collector you can overload new operator and intimate garbage collector every time you allocate memory.

How will you overload << operator for output? Why you have to make it friend ? Becoz, the leftmost operand in overloading << operator should be ostream& , while in member function the leftmost operand is implicitly *this pointer of class. parashift.com/c++-faq-lite/input-output.html#faq-15.8 Name the operators that cannot be overloaded?? sizeof, ., .*, .->, ::, ?:

Can an object be passed by value instead of reference as a parameter while overloading assignment operator ?
Yes you can but there is problem in doing so…
when you will pass the object by value then copy constructor will be called because It satisfy one of the condition that whenever an object is passed by value to a function copy constructor is called. Then your assignment operator will be executed….

Its good to have const just to make sure you are not changing anything inside the implementation.
when you will provide overloaded new operator. give example
when information stored in ‘front of block allocated’ is greater than the block itself e.g. you are allocating characters using new. the info to locate this block / info to locate next free block/info to locate next allocated block will be much larger than the data itself.
Another use thought I am not 100% sure is when you want to place your object at a specific location in the memory
When you want to use your own memory management instead of the default one.
Effectively, if you want to avoid heap fragmentation. If suppose different size of memory is going to get allocate everytime, we might run out of big chunk of memory which might reduce the performance, so you can handle your own memory by creating fixed amount of memory for a particular object.

This need will be highly in the case of real time embedded applications.

What is inline function??
The __inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler’s discretion. For example, the compiler does not inline a function if its address is taken or if it is too large to inline.
Can you overload a function based only on whether a parameter is a value or a reference?
No. Passing by value and by reference looks identical to the caller.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview questions with overriding with code samples

C++ interview questions with overriding

Overriding:

if base class function and overriding function has different return type how it will impact into main program. lets say base class function is returning int which is virtual and derived class function is returning is String.
and I have base* b = new derived()
so can I call int i = b->function() which is derived class function returning string?
Napolean: overriding does not depend on return type. it depends on function name and signature.
so it wont be compiler error.

this will not work. return type is included when comparing the signature. (at least with C++ it is

Napolean is right. Should not have any compiler error. If you want access function in base class from derived instance, you can do

int i = b->Base::function();
it will return string
I think BabelFish was right. The following code won’t compile in VS 2008.

class Base
{
public:
Base() {};
virtual ~Base() {};

virtual int foo() { cout << "base foo" << '\n'; }; }; class Derived : public Base { public: Derived() {}; ~Derived() {}; void foo() { cout << "derived foo" << '\n'; }; }; Anonymous on April 08, 2010 |Edit | Edit Should be: virtual int foo() { cout << "base foo" << '\n'; return 0; }; Nevertheless it won't compile. ur right error C2555: 'Derived::foo': overriding virtual function return type differs and is not covariant from 'Base::foo' You cannot change the return type of virtual function. its an error in C++, if class B is a subtype of class A, then all member functions of B must return the same or narrower set of types as A and string is wider than int... Confliciting return type error is thrown by compiler in such situation. nothing like more or less restrictions/ What is Overriding? To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list. The definition of the method overriding is: • Must have same method name. • Must have same data type. • Must have same argument list. Overriding a method means that replacing a method functionality in child class. To imply overriding functionality we need parent and child classes. In the child class you define the same method signature as one defined in the parent class.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ virtual interview questions like pure virtual constructors, pure constructors, and pure destructors

Virtual:

How do virtual function works in C++? What if the function is not declared virtual?

just read this:
http://www.parashift.com/c++-faq-lite/virtual-functions.html

Explain how virtual functions are implemented.
aka Dynamic binding.

Typically, the pointer’s type determines the function calls. However, virtual functions let the object (not pointer) determines function called.
The base type pointer, calls the method but the proper virtual function at runtime is called (dynamically).

Declare a function as virtual in base class, then override it in each derived class, just like redefining, new function must have same signature. If function declared virtual, can only be overridden. Once declared virtual, a function is virtual in all derived classes. It’s a good practice to explicitly declare virtual though.

Dynamic binding chooses proper function to call of the virtual address table at runtime, but it only occurs off pointer handles. If function called from object, it uses that object’s definition.

I think the answer should be in terms of v-table and v-pointer.

A virtual-table is created for every class having one or more virtual functions. The
virtual table is usually implemented as an array of function pointers where each function pointer corresponds to the various implementations of the virtual function by the derived classes.

When an object of this class is created, it contains a virtual-pointer (v-pointer) which points to the start of v-table. Whenever a virtual function is invoked on this object, the runtime system resolves it by following the v-pointer to the v-table to invoke the appropriate function.

Why do you use virtual functions? What is a VTABLE? How does it work?
Virtual functions are used to extend the polymorphic behavior. You can use them when you want to call the implementation of the derived class member function using a base class pointer.
VPT:- every class has its own virtual function pointer table. It consist of its virtual functions in an organized way which helps compiler to determine which function to call at run time.

e.g
class A{
public:
virtual void print(){cout<<"A";} }; class B:public A{ public: void print(){cout<<"B";} }; void main() { A* a; B b; a=&b; a->print();
}

http://www.go4expert.com/forums/showthread.php?t=8403

This would help us understand 4 byte vptr in a concise manner.

2. why need virtual function in C++?
Object oriented feature Polymorphism is acheived using ‘virtual functions’.

Polymorphism allows imporved code organization and readability.

In addition, importantly, vitual functions allow to create ‘extensible’ programs that can be grown not only during the original creation of objects, but also when new features are added.

Hope this helps.
It will provide the Run time polymorphism to C++. It determines the function calls at the run time.
When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

Virtual functions ensure that the correct function is called for an object, regardless of the expression used to make the function call

Virtual Functions and its implementation

Virtual Functions are implemented usign the vtable, which is a table of function pointers for each of the virtual function present in the class.
The class creates a vtable upon call of its constructor. In case of derived class ,base class creates the initial vtable but constructor of derived class over-rides the entry in the vtable if the virtual function is defined in derived class.

Why does your class have a pure virtual function?

A. To ensure that this function is overridden in derived classes
that are to be instantiated
B. To allow for templated classes to be used with friend functions
C. To maximize the memory efficiency provided that execution speed
is not at a premium
D. To maximize code reuse
E. To maximize the execution speed of the function provided that
memory is not at a premium

yup…It should be A
===

What is virtual function?
When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
class parent
{
void Show()
{
cout << "i'm parent" << endl; } }; class child: public parent { void Show() { cout << "i'm child" << endl; } }; parent * parent_object_ptr = new child; parent_object_ptr->show() // calls parent->show() i
now we goto virtual world…
class parent
{
virtual void Show()
{
cout << "i'm parent" << endl; } }; class child: public parent { void Show() { cout << "i'm child" << endl; } }; parent * parent_object_ptr = new child; parent_object_ptr->show() // calls child->show()

What is pure virtual function? or what is abstract class?
When you define only function prototype in a base class without implementation and do the complete implementation in derived class. This base class is called abstract class and client won’t able to instantiate an object using this base class.
You can make a pure virtual function or abstract class this way..
class Boo
{
void foo() = 0;
}
Boo MyBoo; // compilation error

How virtual functions are implemented C++?
Virtual functions are implemented using a table of function pointers, called the vtable. There is one entry in the table per virtual function in the class. This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed first which creates the vtable. If the derived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you should never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions
What is Virtual Destructor?
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.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview questions on reference, reference vs pointer, pass by reference

C++ interview questions on reference, reference vs pointer, pass by reference
Reference:

What’s the difference between pointer and reference
Reference is to one object can not be changed to another object
Reference should be initialized always.
Any other Differences??
POINTER

1) Its not necessary to initialize the pointer at the time of declaration. Like

int a = 10;

int *P = &a; //It is not necessary

Another way is :

int a = 10;

int *P;
P = &a;

2) You can create the array of Pointer.

3) You can assign NULL to the pointer like

int *P = NULL; //Valid

4) You can use pointer to pointer.

REFERENCE

1) Its necessary to initialize the Reference at the time of declaration. Like

int &a = 10;

int &a; //Error here but not in case of Pointer.

2) You can not create the Array of reference.

3) You can not assign NULL to the reference like

int &a = NULL; //Error

4) You can not use reference to reference.
Is reference a pointer?

* Reference is an implicit pointer
* Must tell it which variable it will become an alias for
* References do not require dereferencing
* No acquisition of memory address required
* References are often implemented by the compiler writers as pointers.
* References are “safer”

Is there any adv of references over pointers?

* References do not require dereferencing
* No acquisition of memory address required
* References are “safer”

Is there any adv of pointers over references? (yes, both this and the last qn is valid)

* Pointer can be left uninitialized.
* Pointer can be stored in Container classes, References cannot, as they are uninitialized.
* Most programs has “NULL” values, Pointers are recommended in these cases.
* Pointer can easily visualize side-effect is local or not.

Where do you initialize a non-static class member that is a reference?
Choice 1

Member initialization list only
Choice 2

Body of constructor only
Choice 3

Point of declaration only
Choice 4

Member initialization list and body of constructor
Choice 5

Point of declaration and member initialization list
5
Member initialization list only
I think its only at the point of declaration, a reference is initialized…
body of constructor only
100% Member initialization list only
Member initialization list.

What is the main reason for using pass by reference over pass by pointer
It’s safer, since we cannot pass by reference with null value

void foo(int &x){
//cout<

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!