Some C++ questions

1. What does the following do:
void afunction(int *x)
{
x=new int;
*x=12;
}
int main()
{
int v=10;
afunction(&v);
cout<<v;
}
a) Outputs 12
b) Outputs 10
c) Outputs the address of v
Ans b.
2. How long does this loop run: for(int x=0; x=3; x++)
a) Never
b) Three times
c) Forever
Ans c.
3. Which uses less memory?
a)
struct astruct
{
int x;
float y;
int v;
};b)
union aunion
{
int x;
float v;
};

c)
char array[10];

Ans b.
4. Evaluate:
int fn(int v)
{
if(v==1 || v==0)
return 1;
if(v%2==0)
return fn(v/2)+2;
else
return fn(v-1)+3;
}
for fn(7);a) 10
b) 11
c) 1
Ans b.
5. Which of the Standard C++ casts can be used to perform a “safe” downcast:
a) reinterpret_cast
b) dynamic_cast
c) static_cast
d) const_cast
Ans b.
6. class professor {};
class teacher : public virtual professor {};
class researcher : public virtual professor {};
class myprofessor : public teacher, public researcher {};

Referring to the sample code above, if an object of class “myprofessor” were created, how many instances of professor will it contain?

a) 0
b) 1
c) 2
d) 3
e) 4
Ans b. , here professor will be called a virtual base class since teacher and researcher derive from it virtually. This is used in multiple inheritance as shown here. If professor was not inherited virtually then there would be 2 instances of professor in the object of myprofessor.
7. string somestring ;
Which of the following choices will convert a standard C++ string object “somestring” to a C string?
a) Copy.somestring () ;
b) somestring.c_str ()
c) &somestring [1]
d) std::cstring (somestring)
e) (char *) somestring
Ans. b
8.
class basex
{
int x;
public:
void setx(int y) {x=y;}
};
class derived : basex {};
What is the access level for the member function “setx” in the class “derived” above?
a) private
b) local
c) global
d) public
e) protected
Ans. a
Table of Member Access Privileges

Access in Base Class Base Class Inherited as Access in
Derived Class
Public Protected Private Public Public Protected No access*
Public Protected Private Protected Public Protected No access*
Public Protected Private Private Public Protected No access*

* Unless friend declarations within the base class explicitly grant access.
So, the highest member accessibility is defined by the way a class is inherited, if it is inherited privately, then the highest member accessibility will be private. Default inheritance is private.

9.
class Alpha {
public:
char data[10000];
Alpha();
~Alpha();
};
class Beta {
public:
Beta() { n = 0; }
void FillData(Alpha a);
private:
int n;
};
How do you make the above sample code more efficient?
a) If possible, make the constructor for Beta private to reduce the overhead of public constructors.
b) Change the return type in FillData to int to negate the implicit return conversion from “int” to “void”.
c) Make the destructor for Alpha virtual.
d) Make the constructor for Alpha virtual.
e) Pass a const reference to Alpha in FillData
Ans e. since u r passing a reference hence a new array will not be created in memory, whereas if u pass by value, then an array of 10000 chars will be created. Passing by reference only creates an alias for the original parameter (i.e., it points to the original parameter) and is same as passing by address, the only difference is that it can be used like an object instead of as a pointer, i.e., if param is &a, then u will write a.member, whereas if param is *a then u will write a->member.
10.
class Foo {
int x;
public:
Foo(int I);
};
If a class does not have a copy constructor explicitly defined one will be implicitly defined for it. Referring to the sample code above, which one of the following declarations is the implicitly created copy constructor?
a) Foo(Foo *f);
b) Foo(Foo &f);
c) Foo(const Foo *f);
d) Foo(const Foo &f);
e) Foo(int);
Ans d. copy constructor takes an arg of its own type which is passed by ref and which should not be changed hence it is const
11.
class HasStatic {
static int I;
};
Referring to the sample code above, what is the appropriate method of defining the member variable “I”, and assigning it the value 10, outside of the class declaration?
a) HasStatic I = 10;
b) int static I = 10;
c) static I(10);
d) static I = 10;
e) int HasStatic::I = 10;
Ans. e
12.
class X
{
private:
int a;
protected:
X(){cout<<”X constructor was called”<<endl;}
~X(){cout<<”X destructor was called”<<endl}
};
Referring to the code above, which one of the following statements regarding “X” is TRUE?
a) X is an abstract class.
b) Only subclasses of X may create X objects.
c) Instances of X cannot be created.
d) X objects can only be created using the default copy constructor.
e) Only friends can create instances of X objects.
Ans b. instances of X can be created only inside its subclasses.
13.
class Foo {
const int x;
protected:
Foo(int f);
~Foo();
};
Foo f;
Referring to the sample code above, why will the class declaration not compile?
a) The variable x is const.
b) The destructor is protected.
c) The destructor is not public.
d) The constructor is protected.
e) There is no default constructor.
Ans e. if u don’t specify a constructor for a class, then the compiler generates the default constructor for u, but if u specify a constructor apart from the default constructor, then u must give the default constructor also, but only if u r creating an object which uses the default constructor. i.e., the following code is perfectly fine
class Foo {
public:
Foo(int f){}
~Foo(){}
};
Foo f(0);But if u try to create an object of Foo like this
Foo f;
then this will give compiler error because there is no default constructor available
14.
class Foo {
public:
Foo(int i) { }
};
class Bar : virtual Foo {
public:
Bar() { }
};
Bar b;

Referring to the above code, when the object ‘b’ is defined, a compiler error will occur. What action fixes the compiler error?

a) Adding a virtual destructor to the class Bar
b) Adding a constructor to Bar which takes an int parameter
c) Adding “Foo()” to the Bar constructor
d) Adding a copy constructor to the class Foo
e) Adding “Foo(0)” to the Bar::Bar initializer list
Ans e.
15. Which one of the following describes characteristics of “protected” inheritance?
a) The base class has access only to the public or protected members of the derived class.
b) The derived class has non-public, inheritable, access to all but the private members of the base class.
c) The derived class has access to all members of the base class.
d) The private members of the base class are visible within the derived class.
e) Public members of the derived class are privately accessible from the base class.
Ans b.
16. The “virtual” specifier in a member function enables which one of the following?
a) Monmorphism
b) Late binding
c) Metamorphism
d) Solomorphism
e) Inheritance
Ans b. consider a base class B having a virtual function Foo, and a class D derived from this class also having a function Foo. Then when u create an object of a derived class, say dobj, and a ptr to base class, say pb, and point pb to dobj by saying pb = &dobj, and then call pb->Foo then the correct version of Foo will be called, i.e., the version in D will be called becz the object is of type D. this is called late binding, i.e., deferring the decision of calling which version of Foo until runtime since at compile time the type of object to which pb points may not be known.
class B {public: virtual void Foo(){cout<<”base”;}};
class D : public B {public: virtual void Foo(){cout<<”derv”;}};
D dobj;
B *pb;
pb = &dobj;
pb->Foo();the output will be ‘derv’.
If Foo was not declared virtual in base class B , then the output would have been ‘base’.
17.
class X
{
public:
int x;
static void f(int z);
};
void X::f(int y) {x=y;}
What is the error in the sample code above?
a) The class X does not have any protected members.
b) The static member function f() accesses the non-static z.
c) The static member function f() accesses the non-static x.
d) The member function f() must return a value.
e) The class X does not have any private members.
Ans c.
18.
template<class T, class X> class Obj {
T my_t;
X my_x;
public:
Obj(T t, X x) : my_t(t), my_x(x) { }
};
Referring to the sample code above, which one of the following is a valid conversion operator for the type T?
a) T operator T () { return my_t; }
b) T operator(T) const { return my_t; }
c) operator(T) { return my_t; }
d) T operator T (const Obj &obj) { return obj.my_t; }
e) operator T () const { return my_t; }
Ans e.
T his will be used for casting objects of type Obj to type T

class Myclass{};
template<class T, class X> class Obj {
T my_t;
X my_x;
public:
Obj(T t, X x) : my_t(t), my_x(x) { }
operator T () const { return my_t; }
operator X () const { return my_x; }
};

void main()
{
Myclass mt;
Obj <int , Myclass > myobj(10,mt);
int x = (int) myobj;
cout << x;
Myclass mobj = (Myclass) myobj;

19.
catch(exception &e)
{
. . .
}
Referring to the sample code above, which one of the following lines of code produces a written description of the type of exception that “e” refers to?
a) cout << e.type();
b) cout << e.name();
c) cout << typeid(e).name();
d) cout << e.what();
e) cout << e;
Ans. c
20.
int f() {
int I = 12;
int &r = I;
r += r / 4;
int *p = &r;
*p += r;
return I;
}
Referring to the sample code above, what is the return value of the function “f()”?
a) 12
b) 15
c) 24
d) 17
e) 30
Ans e.

Simple simulation of MS-DOS prompt

// very very simple indeed

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std ;

void dir() ;
void help() ;
void prompt() ;
void run() ;
void thankyou() ;

int main()
{
string input ;

while(input != “exit”)
{
prompt() ;
cin >> input ;
if(input == “help”) help() ;
if(input == “run”) run() ;
if(input == “dir”) dir() ;
}

thankyou() ;

return 0 ;
}

void prompt()
{
system(“cls”) ;
cout << “C:\\” ;
}

void help()
{
cout << “exit – quit the program” << endl ;
cout << “help – help menu” << endl ;
cout << “run  – run your program” << endl ;
cout << “dir  – display directory contents” << endl ;
system(“pause”) ;
}

void thankyou()
{
cout << “Thank You for Using” << endl ;
cout << “     JustinDOS” << endl ;
system(“pause”) ;
}

void dir()
{
cout << “Directory Contents…” << endl ;
cout << “hello.cpp  122 xxrxx ” << endl ;
cout << “bye.cpp     79 xxxrx ” << endl ;
cout << “NEW_FOLDER” << endl ;
cout << “test.cpp   232 xrxxx ” << endl ;
system(“pause”) ;
}

void run()
{
cout << “Your program will now run…” << endl ;
system(“pause”) ;
for(int i = 1 ; i <= 10 ; i++)
{
cout << i ;
if(i < 10) cout << “-” ;
else cout << endl ;
}
system(“pause”) ;
}

Be Consistent

// BE CONSISTENT
// DO THINGS THE SAME WAY EVERY TIME
// (don't do something one way one time, and a
//  different way the next time)
// use the following as an example only (pretend it's a bigger program)
 // BAD EXAMPLE....(notice the incrementation is done a different way each time even though it's doing the SAME THING!!!!)
 #include   int main()
{      int mynumber = 0 ;
//      // other code...
//       mynumber = mynumber + 1 ;
 cout << "my number incremented by one is..." << mynumber ;
   //      // other code...
  //       mynumber += 1 ;
 cout << "my number incremented by one again is..." << mynumber ;
//      // other code...      //
mynumber++ ;
 cout << "my number incremented once more is..." << mynumber ;
 return 0 ;
}
// GOOD EXAMPLE.... (notice the incrementation is done the same way each time)
 #include   int main()
 {      int mynumber = 0 ;
 //      // other code...      //
 mynumber = mynumber + 1 ;
 cout << "my number incremented by one is..." << mynumber ;
   //      // other code...      //
 mynumber = mynumber + 1 ;
  cout << "my number incremented by one again is..." << mynumber ;
    //      // other code...      //
   mynumber = mynumber + 1 ;
   cout << "my number incremented once more is..." << mynumber ;
 return 0 ;
}

geovisit();

Default in switches

#include

int main()
{
   int x = 17 ;
   switch(x){
       case 1:
       case 5:
       case 9:
           cout << “good job” << endl;
           break;
       default:
           // default catches anything else
           // in this example any time x is
           // not 1, 5, or 9
           // default will catch it
           // you don’t have to have a default
           // but it’s usually helpful
           // you also don’t have to break out of a default!
           cout << “Try again!” << endl ;
     }
}

Posted in Uncategorized. Leave a Comment »

Consistent variable names

int main(){      // I recommend using either this style for variable names      // in which you capitalize each new word      int theName ;      int theOtherName ;      int yetAnotherName ;       // or using this style in which you put an underscore      // between each new word      int the_name;       int the_other_name ;      int yet_another_name ;            // but just don't mix the two, please!      // DON'T MIX THEM PLEASE, pick either one style or the other      // BAD!      /*      int theName ;      int the_other_name ;      int yetAnother_name ;      */       return  0 ; }

Posted in Uncategorized. Leave a Comment »

Program to reverse a Linked list within the same list

#include

typedef struct Link {
int val;
struct Link *next;
} Link;

/* Reverse List function */
Link *SL_reverse(Link *head)
{
Link *revlist = (Link *)0;

while(head) {
Link *tmp;

tmp = head;
head = head->next;
tmp->next = revlist;
revlist = tmp;
}

return revlist;
}

/* Supporting (Verification) routines */

Link *SL_build();

main()
{
Link *head;

head = SL_build();
head = SL_reverse(head);

printf(“\nReversed List\n\n”);
while(head) {
printf(“%d “, head->val);
head = head->next;
}
}
Link *SL_build()
{
Link *head, *prev;

head = prev = (Link *)0;

while(1) {
Link *new;
int val;

printf(“Enter List element [ 0 for end ] : “);
scanf(“%d”, &val);
if (val == 0) break;

new = (Link *) malloc(sizeof(Link));
new->val = val;
if (prev) prev->next = new;
else head = new;
prev = new;
}

prev->next = (Link *)0;
return head;
}

Posted in Uncategorized. Leave a Comment »

Algorithm to check if the link list is in Ascending order

template
bool linklist::isAscending() const{
nodeptr ptr = head;
while(ptr->_next)
{
if(ptr->_data > ptr->_next->_data)
return false;

ptr= ptr->_next;
}
return true;
}

Posted in Uncategorized. Leave a Comment »

Why cant one make an object of abstract class?

we cant make object of abstract class because, in the vtable the vtable entry for the abstract class functions will be NULL, which ever are defined as pure virtual functions…

even if there is a single pure virtual function in the class the class becomes as abstract class…

if there is a virtual function in your class the compiler automatically creates a table called virtual function table… to store the virtual function addresses… if the function is a pure virtual function the vtable entry for that function will be NULL.

even if there is a single NULL entry in the function table the compiler does not allow to create the object…
 

Difference between hard link and soft link in UNIX

Hard Links :

1. All Links have same inode number.

2.ls -l command shows all the links with the link column(Second) shows No. of links.

3. Links have actual file contents

4.Removing any link ,just reduces the link count , but doesn’t affect other links.

Soft Links(Symbolic Links) :

1.Links have different inode numbers.

2. ls -l command shows all links with second column value 1 and the link points to original file.

3. Link has the path for original file and not the contents.

4.Removing soft link doesn’t affect anything but removing original file ,the link becomes “dangling” link which points to nonexistant file.

Posted in Unix. 3 Comments »

Short-hand form of communication.

Many of my friends ask me what is BRB for the first time..If you do not interact online, chances are that you will not be knowing most of the terms like IMO, BTW, CU, OO etc. Well dont worry… You have dropped in the right place… Check this site that contains hundreds of such short forms used in conversation as a sort of short-hand form of communication.

Short forms of communication

Here is some
AKA = Also Known As
ASAP = As Soon As Possible
ASL = Age/Sex/Location
BRB= Be Right Back
CU = See You
CUL8R = See You Later
FYI = For Your Information
IMHO = In My Humble Opinion
IOW = In Other Words
K = Ok
LOL = laughing out loud
MYOB = mind your own business
RSVP = Repondez, s’il vous plait (Respond, please)
W/O = without.” W/ means “with.”
WTG = way to go