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
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.
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. #
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"; }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;
- 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
- Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.
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.
- #include <iostream>
- using namespace std;
- class Animal {
- public:
- void eat() {
- cout<<"Eating..."<<endl;
- }
- };
- class Dog: public Animal
- {
- public:
- void bark(){
- cout<<"Barking..."<<endl;
- }
- };
- class BabyDog: public Dog
- {
- public:
- void weep() {
- cout<<"Weeping...";
- }
- };
- int main(void) {
- BabyDog d1;
- d1.eat();
- d1.bark();
- d1.weep();
- return 0;
- }
- Hierarchical inheritance :
- Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more classes.
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.
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;
}