0% found this document useful (0 votes)
11 views9 pages

BCS-031

Assignment Solution

Uploaded by

Md Qasim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

BCS-031

Assignment Solution

Uploaded by

Md Qasim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Q1. What is a Virtual Constructor? What are its advantages?

Explain with examples. (30 Marks)


In object-oriented programming (OOP), the concept of a "Virtual Constructor" is somewhat misleading,
because constructors cannot be virtual in languages like C++.

However, the term "Virtual Constructor" is used in certain contexts to refer to design patterns that
emulate the behavior of a virtual function but for object creation. The goal of this design pattern is to create
objects at runtime based on dynamic conditions.

Since a constructor's main job is to initialize an object when it's created, and because the constructor is
invoked automatically during object creation, it cannot be virtual in the way that member functions can.
But using techniques like the Factory Design Pattern, you can achieve something close to a virtual
constructor.

Understanding Virtual Constructor with Factory Pattern


The Factory Pattern acts like a virtual constructor. It involves a base class with a method that creates
objects of derived classes dynamically. This pattern allows you to instantiate objects of derived types
without knowing their exact type at compile-time.

Advantages of a Virtual Constructor (Factory Pattern)


1. Encapsulation:
Helps to encapsulate the object creation logic, making the code cleaner and easier to maintain.
2. Decoupling:
Clients do not need to know the exact derived class type; they only work with the base class
interface. This leads to a loosely coupled system.
3. Flexibility:
You can introduce new classes or types without modifying the existing code, thus following the
Open-Closed Principle of software design.
4. Dynamic Object Creation:
Based on conditions, the factory method can return different types of objects at runtime.

Example of Virtual Constructor using Factory Pattern in C++


#include <iostream> language-cpp
using namespace std;

// Step 1: Base class


class Shape {
public:
// Virtual function for displaying shape
virtual void draw() = 0;

// Factory Method acting as a "Virtual Constructor"


static Shape* createShape(int type);
};

// Step 2: Derived classes


class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle" << endl;
}
};

class Square : public Shape {


public:
void draw() override {
cout << "Drawing a Square" << endl;
}
};

// Step 3: Implementing the factory method


Shape* Shape::createShape(int type) {
if (type == 1) return new Circle();
else if (type == 2) return new Square();
else return nullptr;
}

// Main function to demonstrate the concept


int main() {
// Create Circle object
Shape* shape1 = Shape::createShape(1);
if (shape1) shape1->draw();

// Create Square object


Shape* shape2 = Shape::createShape(2);
if (shape2) shape2->draw();

// Clean up memory
delete shape1;
delete shape2;

return 0;
}

Explanation of the Code


1. Abstract Base Class (Shape):
Shape is an abstract base class with a pure virtual function draw() .
The createShape() static method acts as a factory method (a virtual constructor).
2. Derived Classes (Circle, Square):
Circle and Square classes inherit from the Shape class and provide their own
implementation of the draw() function.
3. Factory Method ( createShape() ):
This method takes an integer type as input and returns a pointer to a dynamically created
object of the derived class ( Circle or Square ).
4. Main Function:
The client code can create shapes without knowing the exact type of the object at compile time.
The factory method handles the object creation based on the type.

Output of the Program


Drawing a Circle
Drawing a Square

Q2. What is a Virtual Function? How does it differ from a Pure


Virtual Function? Explain with examples. (30 Marks)

Virtual Function vs Pure Virtual Function


In object-oriented programming (OOP), virtual functions and pure virtual functions are important
concepts related to polymorphism. They are both used to enable dynamic binding in C++, allowing the
correct function to be called based on the object type at runtime rather than the type of the pointer/reference.

Let’s break these concepts down with detailed explanations and examples.

Virtual Function
A virtual function is a function defined in a base class that is intended to be overridden by derived
classes. When you use a base class pointer or reference to call the function, the appropriate function from
the derived class is called at runtime, not the base class function. This is known as dynamic dispatch or
runtime polymorphism.
Key Characteristics of a Virtual Function:
Defined in the base class with the virtual keyword.
Can be overridden by any derived class.
When called through a base class pointer or reference, the correct derived class function is called, even
if the pointer/reference is of the base class type.
The base class function can have a default implementation, which can be optionally overridden in
derived classes.

Example of a Virtual Function in C++


#include <iostream> language-cpp
using namespace std;

// Base class
class Animal {
public:
// Virtual function
virtual void speak() {
cout << "Animal makes a sound" << endl;
}
};

// Derived class 1
class Dog : public Animal {
public:
// Overriding the virtual function
void speak() override {
cout << "Dog barks" << endl;
}
};

// Derived class 2
class Cat : public Animal {
public:
// Overriding the virtual function
void speak() override {
cout << "Cat meows" << endl;
}
};

int main() {
Animal* animal1 = new Dog(); // Create a Dog object
Animal* animal2 = new Cat(); // Create a Cat object

// Calling the speak function (dynamic dispatch)


animal1->speak(); // Output: Dog barks
animal2->speak(); // Output: Cat meows

delete animal1;
delete animal2;

return 0;
}
Pure Virtual Function
A pure virtual function is a function that is declared in the base class but has no implementation in the
base class. It is meant to be overridden by derived classes. A class containing at least one pure virtual
function is called an abstract class, and you cannot instantiate an object of that class directly.

Key Characteristics of a Pure Virtual Function:


Defined in the base class with = 0 at the end of the function declaration.
Does not have any implementation in the base class.
Forces derived classes to provide an implementation for the function.
The class containing the pure virtual function becomes an abstract class, meaning it cannot be
instantiated.

Example of a Pure Virtual Function in C++


#include <iostream> language-cpp
using namespace std;

// Base class with a pure virtual function


class Animal {
public:
// Pure virtual function (no implementation in base class)
virtual void speak() = 0;

// Virtual destructor
virtual ~Animal() {}
};

// Derived class 1
class Dog : public Animal {
public:
// Providing implementation for the pure virtual function
void speak() override {
cout << "Dog barks" << endl;
}
};

// Derived class 2
class Cat : public Animal {
public:
// Providing implementation for the pure virtual function
void speak() override {
cout << "Cat meows" << endl;
}
};

int main() {
// Animal animal; // Error: Cannot instantiate abstract class

Animal* animal1 = new Dog(); // Create a Dog object


Animal* animal2 = new Cat(); // Create a Cat object

animal1->speak(); // Output: Dog barks


animal2->speak(); // Output: Cat meows
delete animal1;
delete animal2;

return 0;
}

Key Differences Between Virtual and Pure Virtual Functions


Feature Virtual Function Pure Virtual Function
Definition Can have an implementation in the base Has no implementation in the base class.
class.
Purpose Allows derived classes to override and extend Forces derived classes to provide their
behavior. own implementation.
Class Type The class can be instantiated if there are no The class is abstract, and objects cannot
pure virtual functions. be instantiated.
Implementation in Base Can have a default implementation. No implementation in the base class.
Class
Syntax virtual void speak() { ... } virtual void speak() = 0;

When to Use Each Type


Virtual Function:
Use when you want to provide a default implementation in the base class, but still allow derived
classes to override it.
Example: If all derived classes need to perform some basic behavior, but the exact details should
vary.
Pure Virtual Function:
Use when you want to force derived classes to provide their own implementation of a
function, and the base class is just an interface or a template for the derived classes.
Example: In abstract classes where the base class is only meant to define a common interface for
the derived classes, not provide any behavior itself.

Q3. What is a Header File? Explain any 5 header files along with
their functions. (20 Marks)

Header File
A header file in C and C++ programming is a file that contains declarations of functions, classes, constants,
and other entities that are shared across multiple source files. Header files typically have the .h extension
(in C) or .hpp (in C++). These files allow code to be modularized and reused. They usually contain
declarations of functions or variables, while the actual definition of the functions or classes is in the
corresponding source files (with .c or .cpp extensions).
Header files are included in source files using the #include directive. This makes the functions and other
declarations available to the source code.

Why Use Header Files?


1. Modularity: They allow code to be organized into multiple files, making it easier to manage.
2. Code Reusability: Functions or classes declared in header files can be used across multiple source
files.
3. Separation of Declaration and Definition: It separates function prototypes from the actual
implementation, improving code readability and maintainability.
4. Prevention of Redundancy: By including header files, functions and variables are declared only
once, avoiding code duplication.

Common Header Files in C and C++


Here are five commonly used header files along with their functions:

1. <iostream> (C++ Standard Library)


This header file is used in C++ for handling input and output operations using streams.

Functions:
std::cin : Used to take input from the standard input device (keyboard).
std::cout : Used to print output to the standard output device (screen).
std::cerr : Used to output errors to the standard error stream.
std::clog : Used to log information to the standard log stream.

Example Usage:
#include <iostream> language-cpp

int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
std::cout << "You entered: " << x << std::endl;
return 0;
}

2. <stdio.h> (C Standard Library)


This header file is used in C for performing input and output operations, such as reading from and writing to
files, and printing output.

Functions:
printf() : Used to print formatted output to the console.
scanf() : Used to read formatted input from the console.
fopen() : Opens a file for reading or writing.
fclose() : Closes an opened file.
fprintf() : Writes formatted output to a file.

Example Usage:
#include <stdio.h> language-c

int main() {
int x;
printf("Enter a number: ");
scanf("%d", &x);
printf("You entered: %d\n", x);
return 0;
}

3. <math.h> (C Standard Library)


This header file is used in C for performing mathematical operations.

Functions:
sqrt() : Computes the square root of a number.
pow() : Raises a number to a power.
sin() , cos() , tan() : Trigonometric functions that compute sine, cosine, and tangent, respectively.
log() : Computes the natural logarithm of a number.
fabs() : Returns the absolute value of a floating-point number.

Example Usage:
#include <math.h> language-c
#include <stdio.h>

int main() {
double x = 25.0;
printf("Square root of %.2f is %.2f\n", x, sqrt(x));
return 0;
}

4. <string.h> (C Standard Library)


This header file provides functions for manipulating C-style strings (arrays of characters).

Functions:
strlen() : Computes the length of a string.
strcpy() : Copies one string to another.
strcmp() : Compares two strings.
strcat() : Concatenates two strings.
strchr() : Finds the first occurrence of a character in a string.

Example Usage:
#include <string.h> language-c
#include <stdio.h>

int main() {
char str1[] = "Hello";
char str2[] = "World";
strcat(str1, str2); // Concatenate str2 to str1
printf("Concatenated string: %s\n", str1);
return 0;
}

5. <stdlib.h> (C Standard Library)


This header file provides functions for performing memory allocation, process control, and other utility
operations.

Functions:
malloc() : Allocates memory dynamically.
free() : Frees dynamically allocated memory.
exit() : Exits the program with a given status.
atoi() : Converts a string to an integer.
rand() : Generates a random number.

Example Usage:
#include <stdlib.h> language-c
#include <stdio.h>

int main() {
int* ptr = (int*)malloc(sizeof(int)); // Dynamically allocate memory
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
*ptr = 10;
printf("Value: %d\n", *ptr);
free(ptr); // Free allocated memory
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy