Unit 4
Q1. Differentiate between Compile time polymorphism and Runtime polymorphism.
Ans.
Differences b/w compile time
and run time polymorphism.
|
Compile time polymorphism |
Run time polymorphism |
|
The function to be
invoked is known at the compile time. |
The function to be
invoked is known at the run time. |
|
It is also known as
overloading, early binding and static binding. |
It is also known as
overriding, Dynamic binding and late binding. |
|
Overloading is a compile
time polymorphism where more than one method is having the same name but with
the different number of parameters or the type of the parameters. |
Overriding is a run time
polymorphism where more than one method is having the same name, number of
parameters and the type of the parameters. |
|
It is achieved by
function overloading and operator overloading. |
It is achieved by
virtual functions and pointers. |
|
It provides fast
execution as it is known at the compile time. |
It provides slow
execution as it is known at the run time. |
|
It is less flexible as
mainly all the things execute at the compile time. |
It is more flexible as
all the things execute at the run time. |
Q2. Describe function overloading with
suitable program
Ans. .
Function Overloading
When there are multiple functions with the
same name but different parameters, then the functions are said to be
overloaded, hence this is known as Function Overloading. Functions can be
overloaded by changing the number of arguments or/and changing the type of
arguments.
#include <iostream>
using namespace std;
// Function to add two
integers
int add (int a, int b) {
return a + b;
}
// Function to add three
integers
int add (int a, int b, int
c) {
return a + b + c;
}
// Function to add two
double values
double add (double a, double
b) {
return a + b;
}
int main() {
int num1 = 5, num2 = 10, num3 = 20;
double num4 = 5.5, num5 = 10.5;
// Calling different overloaded functions
cout << "Sum of two integers:
" << add(num1, num2) << endl;
cout << "Sum of three integers:
" << add(num1, num2, num3) << endl;
cout << "Sum of two doubles:
" << add(num4, num5) << endl;
return 0;
}
Explanation:
1.
Overloading based on the
number of parameters:
o
The first add() function takes two integers.
o
The second add() function takes three
integers.
2.
Overloading based on
parameter type:
o
The third add() function takes two double
values.
Output :-
Sum of two integers: 15
Sum of three integers: 35
Sum of two doubles: 16
Q3. Explain rules of operator overloading
and overload operator to concatenate two strings.
Ans.
Rules of
Operator Overloading in C++:
1.
Only Existing Operators Can
Be Overloaded:
o
You cannot create new operators; you can only
overload existing operators.
2.
Precedence and Associativity
Remain Unchanged:
o
The precedence and associativity of an
overloaded operator cannot be modified.
3.
Overloading Specific
Operators:
o
Some operators like ::, .*, ., ?: cannot be
overloaded.
4.
At Least One Operand Must Be
User-Defined:
o
Overloading must involve at least one
user-defined data type (like class or struct) as an operand.
5.
Function Signature Must
Differ:
o
The overloaded operator must have a different
function signature (number or types of parameters).
6.
Operators Cannot Be
Overloaded with Default Arguments:
o
Default arguments are not allowed in operator
overloading.
7.
Friend Function or Member
Function:
o
Operators can be overloaded either as a member
function or as a friend function of a class.
Overloading
the + Operator to Concatenate Two Strings
Below is an example of overloading the +
operator to concatenate two strings using a class:
#include <iostream>
#include <cstring>
using namespace std;
class String {
private:
char* str;
public:
//
Constructor to initialize the string
String(const
char* s = "") {
str =
new char[strlen(s) + 1];
strcpy(str, s);
}
// Copy
constructor
String(const
String& other) {
str =
new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
//
Destructor to deallocate memory
~String() {
delete[]
str;
}
//
Overloading + operator to concatenate two strings
String
operator+(const String& other) {
char*
temp = new char[strlen(str) + strlen(other.str) + 1];
strcpy(temp, str);
strcat(temp, other.str);
String
newString(temp);
delete[]
temp;
return
newString;
}
// Function
to display the string
void
display() const {
cout
<< str << endl;
}
};
int main() {
String
s1("Hello, ");
String
s2("World!");
//
Concatenating strings using overloaded + operator
String s3 =
s1 + s2;
s3.display(); // Output: Hello,
World!
return 0;
}
Explanation:
1.
Constructor:
o
Initializes the string using dynamic memory
allocation.
2.
Overloaded + Operator:
o
Concatenates two String objects using the
C-style strcat() function.
o
A new string is created by allocating
sufficient memory for both strings and concatenating them.
3.
Copy Constructor:
o
Ensures that a deep copy is made when a new
object is initialized from an existing one.
4.
Destructor:
o
Frees dynamically allocated memory to prevent
memory leaks.
5.
Member Function display():
o
Displays the concatenated result.
Sample
Output:
Hello, World!
Summer 2023
Q4. Define polymorphism with its types.
Ans. Polymorphism in C++ refers to the
ability of a function, operator, or object to behave in multiple forms based on
the context. The term itself comes from the Greek words "poly" (many)
and "morph" (form), meaning "many forms." In C++, polymorphism
is a key concept of object-oriented programming (OOP) and allows objects of
different classes to be treated as objects of a common base class.
Types of
Polymorphism in C++:
Polymorphism in C++ can be broadly classified
into two types:
1.
Compile-time Polymorphism
(Static Polymorphism):
o
The type of polymorphism where the decision
about which function to invoke is made at compile time. This is achieved
through:
§ Function Overloading - Function overloading allows multiple
functions with the same name but different parameter lists.
§ Operator Overloading - Operator overloading allows operators like
+, -, *,
etc., to be overloaded so they can work with user-defined types.
2.
Run-time Polymorphism
(Dynamic Polymorphism):
o
In this case, the decision about which
function to invoke is made at run time. This is typically achieved through:
§ Virtual Functions (Method Overriding) - Virtual functions
in C++ enable function overriding where a function in a derived class replaces
a function in the base class. The base class function must be declared virtual.
Q5. State any four rules for virtual
function.
Ans.
A virtual function must be defined in the base class using the virtual
keyword.
Example :
class Base {
public:
virtual void display() {
cout << "Base
class display" << endl;
}
};
Virtual functions are accessed via a base
class pointer or reference.
Example :
Base* ptr =
new Derived();
ptr->display(); // Calls the derived class's version if it's
overridden
A virtual function can be overridden in a
derived class with the same signature.
Example :
class
Derived : public Base {
public:
void display() override { // Override base class function
cout << "Derived class
display" << endl;
}
};
Virtual functions can be made
pure (abstract) by using = 0.
class Base {
public:
virtual void display() =
0; // Pure virtual function
};
class Derived : public Base {
public:
void display() override {
cout <<
"Derived class implementation" << endl;
}
};
Q6. Explain Virtual
function with example. Give the rules for virtual function
Ans.
Refer to
#include<iostream>
using
namespace std;
class
book
(
char
title[30];
char
authorname[30];
char
publication[30];
int
price;
public:
void
accept()
{
cout<<"\n
Enter the title of Book:";
cin>>title;
cout<<"\n
Enter the Book Author Name:";
cin>>authorname;
cout<<"\n
Enter the Publication details";
cin>>publication;
cout<<"\n
Enter the Price of Book:";
cin>>price,
}
void
display()
{
cout<<"\n
Title of the Book:"<<title;
cout<<"\n
The Name of Author is: "<<authorname;
cout<<"\n
The Publication company is:"<<publication;
cout<<"\n
The Price of the Book is:"<<price;
}
};
int
main()
{
book
b, "p;
p=&b;
p->accept();
p->display();
return
0;
}
Q8.
Write a C++ program to overload “+” operator so that it will perform
concatenation of two strings. Use class get data function to accept two strings
#include
<iostream>
#include
<string>
using
namespace std;
class
ConcatenateStrings {
private:
string str;
public:
// Function to accept a string from the
user
void getData() {
cout << "Enter a string:
";
getline(cin, str);
}
// Overload the + operator to concatenate
two strings
ConcatenateStrings operator+(const
ConcatenateStrings& obj) {
ConcatenateStrings temp;
temp.str = this->str + obj.str; // Concatenation of two strings
return temp;
}
// Function to display the concatenated
string
void display() const {
cout << "Concatenated
string: " << str << endl;
}
};
int
main() {
ConcatenateStrings str1, str2, result;
// Get two strings from the user
str1.getData();
str2.getData();
// Use the overloaded + operator to
concatenate the strings
result = str1 + str2;
// Display the result
result.display();
return 0;
}
Outut
:
Enter
a string: Hello
Enter
a string: World
Concatenated
string: HelloWorld
No comments:
Post a Comment