Cpp question paper

 Cpp questions paper : Download now

1,11 . Virtual Function 


A virtual function is a member function which is declared within a base class and is re-defined (overridden) by a derived class. 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 type of reference (or pointer) used for function call.

They are mainly used to achieve Runtime polymorphism

Functions are declared with a virtual keyword in base class.

The resolving of function call is done at runtime.

Rules for Virtual Functions


Virtual functions cannot be static.

A virtual function can be a friend function of another class.

Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.

The prototype of virtual functions should be the same in the base as well as derived class.

They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.

A class may have virtual destructor but it cannot have a virtual constructor.

Program 

#include <iostream>

using namespace std;


class Base {

   public:

    virtual void print() {

        cout << "Base Function" << endl;

    }

};


class Derived : public Base {

   public:

    void print() {

        cout << "Derived Function" << endl;

    }

};


int main() {

    Derived derived1;


    // pointer of Base type that points to derived1

    Base* base1 = &derived1;


    // calls member function of Derived class

    base1->print();


    return 0;

}

Output; 

Derived function 

2.

Exception handling consist of three keywords: try, throw and catch:


The try statement allows you to define a block of code to be tested for errors while it is being executed.


The throw keyword throws an exception when a problem is detected, which lets us create a custom error.


The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


The try and catch keywords come in pairs:


Example

#include <iostream>
using namespace std;
 
int main()
{
    try  {
       throw 10;
    }
    catch (char *excp)  {
        cout << "Caught " << excp;
    }
    catch (...)  {
        cout << "Default Exception\n";
    }
    return 0;
}

output :

Default exception

3. Template function to perform bubble sort on array 

#include<iostream>

using namespace std;

// template function to perform bubble sort on array, arr

// n: size of arr

template<typename T>

void BubbleSort(T arr[], int n)

{

for(int i=0;i<n-1;++i){

for(int j=0;j<n-i-1;++j){

if(arr[j]>arr[j+1]){

T temp = arr[j+1];

arr[j+1] = arr[j];

arr[j] = temp;

}

}

}

}


// Template function to print array

// n: size of arr[]

template<typename T>

void PrintArray(T arr[], int n)

{

    for (int i = 0; i < n; ++i)

        cout << arr[i] << " ";

    cout << "\n\n";

}


int main()

{


    int arr[] = { 1, 10, 90, 100, -1, 11, 9, 14, 3, 2, 20, 19 };

    int n = sizeof(arr) / sizeof(int);


    cout << "Array Before Sorting: " << endl;

    PrintArray(arr, n);


    BubbleSort(arr, n);


    cout << "Array After Sorting: " << endl;

    PrintArray(arr, n);


}

4.) Pointers store address of variables or a memory location.

Syntax:

datatype *var_name; 

Example: pointer “ptr” holds address of an integer variable or holds address of a memory whose value(s) can be accessed as integer values through “ptr”

int *ptr;  

Features of Pointers:

Pointers save memory space.

Execution time with pointers is faster because data are manipulated with the address, that is, direct access to

memory location.

Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well. Hence it can be said the Memory of pointers is dynamically allocated.

Pointers are used with data structures. They are useful for representing two-dimensional and multi-dimensional

arrays.

An array, of any type can be accessed with the help of pointers, without considering its subscript range.

Pointers are used for file handling.

Pointers are used to allocate memory dynamically.

Uses of pointers:

To pass arguments by reference

For accessing array elements

To return multiple values

Dynamic memory allocation

To implement data structures

To do system level programming where memory addresses are useful

5.

 A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined with the pre-processor directive.

#include<stdio.h>
int number()
{
    return 10;
}
int main()
{
    printf("%d", number());
    return 0;
}

output:
10



A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. 

example program :

#include <iostream>

using namespace std;

T myMax(T x, T y)

{

return (x > y)? x: y;

}

int main()

{

cout << myMax<int>(3, 7) << endl;

cout << myMax<double>(3.0, 7.0) << endl;

cout << myMax<char>('g', 'e') << endl;

return 0;

}.


6. 

class third_derived_class: public base_class 

// C++ program to demonstrate hierarchical inheritance


#include <iostream>

using namespace std;


// base class

class Animal {

   public:

    void info() {

        cout << "I am an animal." << endl;

    }

};


// derived class 1

class Dog : public Animal {

   public:

    void bark() {

        cout << "I am a Dog. Woof woof." << endl;

    }

};


// derived class 2

class Cat : public Animal {

   public:

    void meow() {

        cout << "I am a Cat. Meow." << endl;

    }

};


int main() {

    // Create object of Dog class

    Dog dog1;

    cout << "Dog Class:" << endl;

    dog1.info();  // Parent Class function

    dog1.bark();


    // Create object of Cat class

    Cat cat1;

    cout << "\nCat Class:" << endl;

    cat1.info();  // Parent Class function

    cat1.meow();


    return 0;

}

Output:

Dog Class:

I am an animal.

I am a Dog. Woof woof.


Cat Class:

I am an animal.

I am a Cat. Meow.

8. Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

Program 


#include <iostream>
 
using namespace std;

class Box {
   public:
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume() {
         return length * breadth * height;
      }
      int compare(Box box) {
         return this->Volume() > box.Volume();
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   if(Box1.compare(Box2)) {
      cout << "Box2 is smaller than Box1" <<endl;
   } else {
      cout << "Box2 is equal to or larger than Box1" <<endl;
   }
   
   return 0;
}

Output : 


Constructor called.
Constructor called.
Box2 is equal to or larger than Box1

9. #include<iostream>

using namespace std; int main() { int a=10, b=0, c; try { //if a is divided by b(which has a value 0); if(b==0) throw(c); else c=a/b; } catch(char c) //catch block to handle/catch exception { cout<<"Caught exception : char type "; } catch(int i) //catch block to handle/catch exception { cout<<"Caught exception : int type "; } catch(short s) //catch block to handle/catch exception { cout<<"Caught exception : short type "; } cout<<"\n Hello"; }

Output: 

Caught exception : int type Hello

10.
#include <iostream>
using namespace std;


template <typename T>
struct link                          
{
T data;                       
link* next;                      
};

template <class T>
class linklist                      
{
private:
link<T>* first;              
public:
linklist()                      
{ first = NULL; }           
void additem(T d);            
void display();                 
};

template <class T>
void linklist<T>::additem(T d)        
{
link<T> *newLink = new link<T>;
newLink->data = d;
//insert at head of link list
newLink->next = first;
first = newLink;
}
template <class T>
void linklist<T>::display()          
{
link<T>* current = first;            
while( current != NULL )      
{
cout << current->data << endl; 
current = current->next;        
}
}

int main()
{
linklist<int> li;      
li.additem(25);    
li.additem(36);
li.additem(49);
li.display();      

linklist<char> lch;     
lch.additem('a');    
lch.additem('b');
lch.additem('c');
lch.display();     

return 0;

}



12 The Standard Template Library (STL) is a set of  template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite for working with STL. STL has four components 
 
Algorithms
  •  Containers 
  •  Functions 
  • Iterators

Containers

Containers or container classes store objects and data. There are in total seven standard “first-class” container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors.

  • Sequence Containers: implement data structures which can be accessed in a sequential manner.
    • vector
    • list
    • deque
    • arrays
    • forward_list               
  •        FUNCTIONS 
  • The STL includes classes that overload the function call operator. Instances of such classes are called function objects or functors. Functors allow the working of the associated function to be customized with the help of parameters to be passed

    Iterators

    As the name suggests, iterators are used for working upon a sequence of values. They are the major feature that allow generality in STL

13. 
inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically.

types of inheritance
  • Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.
           
  1. #include <iostream>  
  2. using namespace std;  
  3.  class Account {  
  4.    public:  
  5.    float salary = 60000;   
  6.  };  
  7.    class Programmer: public Account {  
  8.    public:  
  9.    float bonus = 5000;    
  10.    };       
  11. int main(void) {  
  12.      Programmer p1;  
  13.      cout<<"Salary: "<<p1.salary<<endl;    
  14.      cout<<"Bonus: "<<p1.bonus<<endl;    
  15.     return 0;  
  16. }  

Output:

Salary: 60000
Bonus: 5000
  • Multi inheritance : When one class inherits another class which is further inherited by another class, it is known as multi level inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of all its base classes.
  1. #include <iostream>  
  2. using namespace std;  
  3.  class Animal {  
  4.    public:  
  5.  void eat() {   
  6.     cout<<"Eating..."<<endl;   
  7.  }    
  8.    };  
  9.    class Dog: public Animal   
  10.    {    
  11.        public:  
  12.      void bark(){  
  13.     cout<<"Barking..."<<endl;   
  14.      }    
  15.    };   
  16.    class BabyDog: public Dog   
  17.    {    
  18.        public:  
  19.      void weep() {  
  20.     cout<<"Weeping...";   
  21.      }    
  22.    };   
  23. int main(void) {  
  24.     BabyDog d1;  
  25.     d1.eat();  
  26.     d1.bark();  
  27.      d1.weep();  
  28.      return 0;  
  29. }  
  • Hierarchical inheritance : 
  •  Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more classes.
  1. #include <iostream>  
  2. using namespace std;  
  3. class A  
  4. {  
  5.     protected:  
  6.      int a;  
  7.     public:  
  8.     void get_a(int n)  
  9.     {  
  10.         a = n;  
  11.     }  
  12. };  
  13.   
  14. class B  
  15. {  
  16.     protected:  
  17.     int b;  
  18.     public:  
  19.     void get_b(int n)  
  20.     {  
  21.         b = n;  
  22.     }  
  23. };  
  24. class C : public A,public B  
  25. {  
  26.    public:  
  27.     void display()  
  28.     {  
  29.         std::cout << "The value of a is : " <<a<< std::endl;  
  30.         std::cout << "The value of b is : " <<b<< std::endl;  
  31.         cout<<"Addition of a and b is : "<<a+b;  
  32.     }  
  33. };  
  34. int main()  
  35. {  
  36.    C c;  
  37.    c.get_a(10);  
  38.    c.get_b(20);  
  39.    c.display();  
  40.   
  41.     return 0;  
  42. }  

Output:

The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
  • Hybrid inheritance  is a combination of more than one type of inheritance.
  1. #include <iostream>  
  2. using namespace std;  
  3. class A  
  4. {  
  5.     protected:  
  6.     int a;  
  7.     public:  
  8.     void get_a()  
  9.     {  
  10.        std::cout << "Enter the value of 'a' : " << std::endl;  
  11.        cin>>a;  
  12.     }  
  13. };  
  14.   
  15. class B : public A   
  16. {  
  17.     protected:  
  18.     int b;  
  19.     public:  
  20.     void get_b()  
  21.     {  
  22.         std::cout << "Enter the value of 'b' : " << std::endl;  
  23.        cin>>b;  
  24.     }  
  25. };  
  26. class C   
  27. {  
  28.     protected:  
  29.     int c;  
  30.     public:  
  31.     void get_c()  
  32.     {  
  33.         std::cout << "Enter the value of c is : " << std::endl;  
  34.         cin>>c;  
  35.     }  
  36. };  
  37.   
  38. class D : public B, public C  
  39. {  
  40.     protected:  
  41.     int d;  
  42.     public:  
  43.     void mul()  
  44.     {  
  45.          get_a();  
  46.          get_b();  
  47.          get_c();  
  48.          std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;  
  49.     }  
  50. };  
  51. int main()  
  52. {  
  53.     D d;  
  54.     d.mul();  
  55.     return 0;  
  56. }  

Output:

Enter the value of 'a' :
10              
Enter the value of 'b' :    
20      
Enter the value of c is :   
30  
Multiplication of a,b,c is : 6000

7. #include <iostream>

 
using namespace std;

class Box {
   public:
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume() {
         return length * breadth * height;
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2
   Box *ptrBox;                // Declare pointer to a class.

   // Save the address of first object
   ptrBox = &Box1;

   // Now try to access a member using member access operator
   cout << "Volume of Box1: " << ptrBox->Volume() << endl;

   // Save the address of second object
   ptrBox = &Box2;

   // Now try to access a member using member access operator
   cout << "Volume of Box2: " << ptrBox->Volume() << endl;
  
   return 0; 
}
Previous Post Next Post