Saturday, October 11, 2008

C++ Interview Question Part#5

Job C++ Interview Question with Answer

C++ Interview Question: What is the difference between char a[] = “string”; and char *p = “string”;?
In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case if *p is assigned to some other value the allocate memory can change.

C++ Interview Question: What’s the auto keyword good for?
It declares an object with automatic storage duration. Which means the object will be destroyed at the end of the objects scope. All variables in functions that are not declared as static and not dynamically allocated have automatic storage duration by default. For exampleint main(){int a; //this is the same as writing “auto int a;”} .variables occur within a scope; they are “local” to a function. They are often called automatic variables because they automatically come into being when the scope is entered and automatically go away when the scope closes. The keyword auto makes this explicit, but local variables default to auto auto auto auto so it is never necessary to declare something as an auto auto auto auto.

C++ Interview Question: What is a dangling pointer?
A dangling pointer arises when you use the address of an object afterits lifetime is over. This may occur in situations like returningaddresses of the automatic variables from a function or using theaddress of the memory block after it is freed. The followingcode snippet shows this:class Sample{public:int *ptr;Sample(int i){ptr = new int(i);}~Sample(){delete ptr;}void PrintVal(){cout << "The value is " << *ptr;}};void SomeFunc(Sample x){cout << "Say i am in someFunc " << endl;}int main(){Sample s1 = 10;SomeFunc(s1);s1.PrintVal();}In the above example when PrintVal() function iscalled it is called by the pointer that has been freed by thedestructor in SomeFunc.

No comments: