Free Solved[June 2023] BCS031 - Programming in C++

Hey there! Welcome to KnowledgeKnot! Don't forget to share this with your friends and revisit often. Your support motivates us to create more content in the future. Thanks for being awesome!

1. (a) What are virtual functions and what are its uses? Explain with example. (5 marks)

Answer:

Virtual functions in C++ are member functions that are declared within a base class and are meant to be overridden in derived classes. They ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for the function call. This is achieved through a mechanism called "dynamic binding" or "late binding". The primary use of virtual functions is to achieve runtime polymorphism.

class Base {
public:
    virtual void show() {
        cout << "Base class" << endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        cout << "Derived class" << endl;
    }
};

int main() {
    Base *b;
    Derived d;
    b = &d;
    b->show();  // Output: Derived class
    return 0;
}

1. (b) How is protected access specifier different from public access specifier? Explain its usage for a subclass. (5 marks)

Answer:

In C++, the protected access specifier allows member variables and functions to be accessed within its own class and by derived classes. The public access specifier allows member variables and functions to be accessed from outside the class as well.

Usage in a subclass:

class Base {
protected:
    int protectedVar;
public:
    int publicVar;
};

class Derived : public Base {
public:
    void show() {
        protectedVar = 1; // Accessible
        publicVar = 2;    // Accessible
    }
};

1. (c) Explain two unique features of object oriented programming over structured programming with example. (5 marks)

Answer:

Two unique features of object-oriented programming (OOP) over structured programming are:

  1. Encapsulation: Encapsulation is the mechanism of wrapping the data (variables) and the code (functions) acting on the data together as a single unit. In OOP, the data is not accessible to the outside world, and only those functions that are wrapped in the class can access it.
  2. Inheritance: Inheritance is the capability of one class to inherit the properties and behaviors from another class. This feature promotes code reusability.
class Base {
protected:
    int baseVar;
public:
    void setBaseVar(int var) {
        baseVar = var;
    }
};

class Derived : public Base {
public:
    void showBaseVar() {
        cout << "Base variable: " << baseVar << endl;
    }
};

int main() {
    Derived d;
    d.setBaseVar(5);
    d.showBaseVar();  // Output: Base variable: 5
    return 0;
}

1. (d) What is the utility of friend function? Does it violate the rule of encapsulation? (5 marks)

Answer:

A friend function in C++ is a function that is not a member of a class but has access to the class's private and protected members. It is declared using the friend keyword inside the class.

While friend functions can access the private data of a class, they do violate the rule of encapsulation to some extent, as they allow external functions to access the class's private members.

class Sample {
private:
    int num;
public:
    Sample() : num(0) {}
    friend void showNum(Sample &s);
};

void showNum(Sample &s) {
    cout << "Number: " << s.num << endl;
}

int main() {
    Sample s;
    showNum(s);  // Output: Number: 0
    return 0;
}

1. (e) Differentiate between early binding and late binding with an example of each. (5 marks)

Answer:

Early binding refers to compile-time binding where the function call is resolved at compile time. Late binding refers to runtime binding where the function call is resolved at runtime.

Early Binding:

class Base {
public:
    void show() {
        cout << "Base class" << endl;
    }
};

int main() {
    Base b;
    b.show();  // Output: Base class
    return 0;
}

Late Binding:

class Base {
public:
    virtual void show() {
        cout << "Base class" << endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        cout << "Derived class" << endl;
    }
};

int main() {
    Base *b = new Derived();
    b->show();  // Output: Derived class
    delete b;
    return 0;
}

1. (f) What are constructors in C++? Mention their five characteristics. (5 marks)

Answer:

Constructors are special member functions of a class that are executed whenever new objects of that class are created. They have the same name as the class and do not have a return type.

Five characteristics of constructors:

  1. They have the same name as the class.
  2. They do not have a return type.
  3. They are automatically called when an object is created.
  4. They can be overloaded.
  5. They cannot be inherited but can call the base class constructor.
class Sample {
public:
    Sample() {
        cout << "Constructor called" << endl;
    }
};

int main() {
    Sample s;  // Output: Constructor called
    return 0;
}

1. (g) What is Runtime Polymorphism? Explain its utility with the help of an example. (5 marks)

Answer:

Runtime polymorphism, also known as dynamic polymorphism, is achieved using function overriding. It allows a function to behave differently based on the object that calls it, which is determined at runtime.

class Base {
public:
    virtual void display() {
        cout << "Display of Base class" << endl;
    }
};

class Derived : public Base {
public:
    void display() override {
        cout << "Display of Derived class" << endl;
    }
};

int main() {
    Base *b = new Derived();
    b->display();  // Output: Display of Derived class
    delete b;
    return 0;
}

1. (h) What is STL? Explain the importance of STL library in C++. (5 marks)

Answer:

STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.

Importance of STL:

  1. Provides a collection of ready-to-use classes and functions.
  2. Encourages code reuse and reduces development time.
  3. Offers efficient and tested algorithms.
  4. Promotes generic programming.

2. (a) What is object oriented programming? Explain the benefits of object oriented programming. (5 marks)

Answer:

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and methods. OOP principles include encapsulation, inheritance, and polymorphism.

Benefits of OOP:

  1. Encapsulation: Protects data by bundling it with methods that can modify it.
  2. Inheritance: Allows new classes to inherit properties and behaviors from existing classes, promoting code reuse.
  3. Polymorphism: Enables objects to be treated as instances of their parent class, improving flexibility and integration of code.
  4. Abstraction: Simplifies complex systems by modeling classes appropriate to the problem domain.

2. (b) Differentiate between automatic and type-casting with the help of an example. (5 marks)

Answer:

Automatic type conversion is performed by the compiler without programmer intervention when two types are compatible. Type-casting is explicit conversion by the programmer to convert one data type to another.

Example:

Automatic Type Conversion:

int a = 5;
double b = a;  // Automatic conversion from int to double

Type-Casting:

double x = 5.5;
int y = (int)x;  // Type-casting from double to int

2. (c) Explain the difference between information hiding and encapsulation with the help of an example. (5 marks)

Answer:

Information hiding is the principle of hiding the internal details and functionality of an object and exposing only what is necessary. Encapsulation is the technique used to implement information hiding by bundling data and methods within a class.

class EncapsulationExample {
private:
    int hiddenData;  // Information hiding
public:
    void setData(int data) {
        hiddenData = data;  // Encapsulation
    }
    int getData() {
        return hiddenData;  // Encapsulation
    }
};

2. (d) Explain the difference between method overloading and method overriding with example. (5 marks)

Answer:

Method overloading allows multiple methods in the same class to have the same name but different parameters. Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass.

Example of Method Overloading:

class Example {
public:
    void display(int a) {
        cout << "Display int: " << a << endl;
    }
    void display(double b) {
        cout << "Display double: " << b << endl;
    }
};

Example of Method Overriding:

class Base {
public:
    virtual void show() {
        cout << "Base show" << endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        cout << "Derived show" << endl;
    }
};

3. (a) What is inheritance? Explain, how inheritance is implemented in C++. (5 marks)

Answer:

Inheritance is an OOP principle where a new class (derived class) inherits properties and behaviors from an existing class (base class). In C++, inheritance is implemented using the : symbol.

class Base {
protected:
    int baseVar;
public:
    void setBaseVar(int var) {
        baseVar = var;
    }
};

class Derived : public Base {
public:
    void showBaseVar() {
        cout << "Base variable: " << baseVar << endl;
    }
};

3. (b) How do inline functions provide efficiency during runtime? Explain. (5 marks)

Answer:

Inline functions are functions defined with the inline keyword, and their function body is inserted directly into the place where they are called. This eliminates the overhead of function calls, making the program run faster.

inline int add(int a, int b) {
    return a + b;
}

int main() {
    cout << add(3, 4);  // Output: 7
    return 0;
}

3. (c) What is the difference between If statement and For loop? Explain with example. (5 marks)

Answer:

An if statement is a conditional statement that executes a block of code if a specified condition is true. A for loop is a control flow statement that allows code to be executed repeatedly based on a condition.

Example of if statement:

int x = 10;
if (x > 5) {
    cout << "x is greater than 5";
}

Example of for loop:

for (int i = 0; i < 5; i++) {
    cout << i << " ";
}

3. (d) What is operator precedence? Explain the order of operator precedence in arithmetical operators in C++ with the help of an example. (5 marks)

Answer:

Operator precedence determines the order in which operators are evaluated in expressions. In C++, arithmetic operators have the following precedence (from highest to lowest):

  1. Multiplication (*), Division (/), Modulus (%)
  2. Addition (+), Subtraction (-)
int result = 10 + 20 * 3 / 2;  // Evaluates to 40

4. (a) Define the term class. How are class and object related? Explain with example. (5 marks)

Answer:

A class in C++ is a user-defined data type that serves as a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data. Objects are instances of a class.

class Sample {
private:
    int data;
public:
    void setData(int d) {
        data = d;
    }
    int getData() {
        return data;
    }
};

int main() {
    Sample s;  // s is an object of class Sample
    s.setData(10);
    cout << s.getData();  // Output: 10
    return 0;
}

4. (b) How is static keyword used in C++? Explain how the static keyword makes a difference when attached to a function. (5 marks)

Answer:

The static keyword in C++ is used to declare static variables and static functions. A static variable retains its value between function calls. A static function is a member function that can be called on the class itself, rather than on instances of the class.

class Sample {
private:
    static int count;
public:
    static void showCount() {
        cout << "Count: " << count << endl;
    }
};

int Sample::count = 0;

int main() {
    Sample::showCount();  // Accessing static function
    return 0;
}

4. (c) Differentiate between member functions and global functions with help of an example. (5 marks)

Answer:

Member functions are functions that are defined within a class and operate on objects of that class. Global functions are functions that are not part of any class and can be called from anywhere in the program.

class Sample {
public:
    void memberFunction() {
        cout << "Member function called" << endl;
    }
};

void globalFunction() {
    cout << "Global function called" << endl;
}

int main() {
    Sample s;
    s.memberFunction();  // Calling member function
    globalFunction();    // Calling global function
    return 0;
}

4. (d) How is memory allocation done in C++ when a class is declared and a class is instantiated? Explain with the help of an example. (5 marks)

Answer:

In C++, memory allocation for a class happens when objects of that class are instantiated. Memory is allocated for member variables but not for member functions. When an object is created, the constructor is called to initialize the object.

class Sample {
private:
    int data;
public:
    Sample() {
        data = 0;
    }
};

int main() {
    Sample s;  // Memory allocated for data
    return 0;
}

5. (a) What is the role of copy constructor? Illustrate the cases when it is invoked. (5 marks)

Answer:

A copy constructor in C++ is a special constructor that initializes an object using another object of the same class. It is used to create a copy of an existing object.

The copy constructor is invoked in the following cases:

  1. When an object is initialized using another object of the same class.
  2. When an object is passed by value to a function.
  3. When an object is returned by value from a function.
class Sample {
public:
    int data;
    Sample(int d) : data(d) {}
    Sample(const Sample &obj) {
        data = obj.data;
    }
};

int main() {
    Sample s1(10);      // Normal constructor
    Sample s2 = s1;     // Copy constructor invoked
    Sample s3(s1);      // Copy constructor invoked
    return 0;
}

5. (b) What are private constructors and destructors? How are they different from constructors and destructors which are not private? Explain. (5 marks)

Answer:

Private constructors and destructors in C++ are constructors and destructors that are declared as private within a class. They restrict the instantiation and destruction of objects from outside the class.

Differences:

  1. Private constructors prevent direct instantiation of the class. Objects can only be created through friend functions or static member functions.
  2. Private destructors prevent direct deletion of objects, which can only be destroyed through friend functions or static member functions.
  3. Non-private constructors and destructors allow objects to be created and destroyed from anywhere in the program.
class Sample {
private:
    Sample() {
        cout << "Constructor called" << endl;
    }
    ~Sample() {
        cout << "Destructor called" << endl;
    }
public:
    static Sample* createInstance() {
        return new Sample();
    }
    static void deleteInstance(Sample *s) {
        delete s;
    }
};

int main() {
    Sample *s = Sample::createInstance();  // Object created through static function
    Sample::deleteInstance(s);             // Object deleted through static function
    return 0;
}

5. (c) What is the role of new operator in C++? Explain. Also explain delete operator. (5 marks)

Answer:

The new operator in C++ dynamically allocates memory on the heap for an object or an array of objects and returns a pointer to the allocated memory. The delete operator deallocates memory that was previously allocated by new.

int *ptr = new int;       // Allocate memory for a single integer
*ptr = 10;
delete ptr;                  // Deallocate memory

int *arr = new int[10];      // Allocate memory for an array of 10 integers
delete[] arr;                // Deallocate memory for the array

5. (d) What are stream manipulators? Briefly explain any two stream manipulators in C++. (5 marks)

Answer:

Stream manipulators in C++ are functions that can be used to control input and output streams. They allow formatting of the stream data.

Two common stream manipulators:

  1. std::setw: Sets the width of the next input/output field.
    #include <iostream>
    #include <iomanip>
    
    int main() {
        std::cout << std::setw(10) << 123 << std::endl;  // Output: "       123"
        return 0;
    }
  2. std::setprecision: Sets the decimal precision for floating-point output.
    #include <iostream>
    #include <iomanip>
    
    int main() {
        double pi = 3.14159265;
        std::cout << std::setprecision(4) << pi << std::endl;  // Output: 3.142
        return 0;
    }