Set - 1

Question 11 :

What is public, protected, private?

Answer :

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.


Question 12 :

Write a function that swaps the values of two integers, using int* as the argument type?

Answer :

void swap(int* a, int*b) {
	int t;
	t = *a;
	*a = *b;
	*b = t;
}

 


Question 13 :

Tell how to check whether a linked list is circular?

Answer :

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\");
	}
}

 


Question 14 :

OK, why does this work?

Answer :

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.


Question 15 :

What is virtual constructors/destructors?

Answer :

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.