BCS-031
BCS-031
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.
// Clean up memory
delete shape1;
delete shape2;
return 0;
}
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.
// 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
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.
// 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
return 0;
}
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.
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;
}
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;
}
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;
}
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;
}
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;
}