Unit 4
Q1. Differentiate between Compile timepolymorphism and Runtime polymorphism.
Ans.
Differences b/w compile timeand 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 withsuitable program
Ans. .
Function Overloading
When there are multiple functions with thesame name but different parameters, then the functions are said to beoverloaded, hence this is known as Function Overloading. Functions can beoverloaded by changing the number of arguments or/and changing the type ofarguments.
#include <iostream>
using namespace std;
// Function to add twointegers
int add (int a, int b) {
return a + b;
}
// Function to add threeintegers
int add (int a, int b, intc) {
return a + b + c;
}
// Function to add twodouble values
double add (double a, doubleb) {
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 thenumber of parameters:
oThe first add() function takes two integers.
oThe second add() function takes threeintegers.
2.Overloading based onparameter type:
oThe third add() function takes two doublevalues.
Output :-
Sum of two integers: 15
Sum of three integers: 35
Sum of two doubles: 16
Q3. Explain rules of operator overloadingand overload operator to concatenate two strings.
Ans.
Rules ofOperator Overloading in C++:
1.Only Existing Operators CanBe Overloaded:
oYou cannot create new operators; you can onlyoverload existing operators.
2.Precedence and AssociativityRemain Unchanged:
oThe precedence and associativity of anoverloaded operator cannot be modified.
3.Overloading SpecificOperators:
oSome operators like ::, .*, ., ?: cannot beoverloaded.
4.At Least One Operand Must BeUser-Defined:
oOverloading must involve at least oneuser-defined data type (like class or struct) as an operand.
5.Function Signature MustDiffer:
oThe overloaded operator must have a differentfunction signature (number or types of parameters).
6.Operators Cannot BeOverloaded with Default Arguments:
oDefault arguments are not allowed in operatoroverloading.
7.Friend Function or MemberFunction:
oOperators can be overloaded either as a memberfunction or as a friend function of a class.
Overloadingthe + 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(constchar* s = "") {
str =new char[strlen(s) + 1];
strcpy(str, s);
}
// Copyconstructor
String(constString& 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
Stringoperator+(const String& other) {
char*temp = new char[strlen(str) + strlen(other.str) + 1];
strcpy(temp, str);
strcat(temp, other.str);
StringnewString(temp);
delete[]temp;
returnnewString;
}
// Functionto display the string
voiddisplay() const {
cout<< str << endl;
}
};
int main() {
Strings1("Hello, ");
Strings2("World!");
//Concatenating strings using overloaded + operator
String s3 =s1 + s2;
s3.display(); // Output: Hello,World!
return 0;
}
Explanation:
1.Constructor:
oInitializes the string using dynamic memoryallocation.
2.Overloaded + Operator:
oConcatenates two String objects using theC-style strcat() function.
oA new string is created by allocatingsufficient memory for both strings and concatenating them.
3.Copy Constructor:
oEnsures that a deep copy is made when a newobject is initialized from an existing one.
4.Destructor:
oFrees dynamically allocated memory to preventmemory leaks.
5.Member Function display():
oDisplays the concatenated result.
SampleOutput:
Hello, World!
Summer 2023
Q4. Define polymorphism with its types.
Ans. Polymorphism in C++ refers to theability of a function, operator, or object to behave in multiple forms based onthe context. The term itself comes from the Greek words "poly" (many)and "morph" (form), meaning "many forms." In C++, polymorphismis a key concept of object-oriented programming (OOP) and allows objects ofdifferent classes to be treated as objects of a common base class.
Types ofPolymorphism in C++:
Polymorphism in C++ can be broadly classifiedinto two types:
1.Compile-time Polymorphism(Static Polymorphism):
oThe type of polymorphism where the decisionabout which function to invoke is made at compile time. This is achievedthrough:
§ Function Overloading - Function overloading allows multiplefunctions 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):
oIn this case, the decision about whichfunction to invoke is made at run time. This is typically achieved through:
§ Virtual Functions (Method Overriding) - Virtual functionsin C++ enable function overriding where a function in a derived class replacesa function in the base class. The base class function must be declared virtual
.
Q5. State any four rules for virtualfunction.
Ans.
A virtual function must be defined in the base class using the virtualkeyword.
Example :
class Base {
public:
virtual void display() {
cout << "Baseclass display" << endl;
}
};
Virtual functions are accessed via a baseclass pointer or reference.
Example :
Base* ptr =new Derived();
ptr->display(); // Calls the derived class's version if it'soverridden
A virtual function can be overridden in aderived class with the same signature.
Example :
classDerived : public Base {
public:
void display() override { // Override base class function
cout << "Derived classdisplay" << endl;
}
};
Virtual functions can be madepure (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 Virtualfunction with example. Give the rules for virtual function
Ans.Refer to
#include<iostream>
usingnamespace std;
classbook
(
chartitle[30];
charauthorname[30];
charpublication[30];
intprice;
public:
voidaccept()
{
cout<<"\nEnter the title of Book:";
cin>>title;
cout<<"\nEnter the Book Author Name:";
cin>>authorname;
cout<<"\nEnter the Publication details";
cin>>publication;
cout<<"\nEnter the Price of Book:";
cin>>price,
}
voiddisplay()
{
cout<<"\nTitle of the Book:"<<title;
cout<<"\nThe Name of Author is: "<<authorname;
cout<<"\nThe Publication company is:"<<publication;
cout<<"\nThe Price of the Book is:"<<price;
}
};
intmain()
{
bookb, "p;
p=&b;
p->accept();
p->display();
return0;
}
Q8.Write a C++ program to overload “+” operator so that it will performconcatenation of two strings. Use class get data function to accept two strings
#include<iostream>
#include<string>
usingnamespace std;
classConcatenateStrings {
private:
string str;
public:
// Function to accept a string from theuser
void getData() {
cout << "Enter a string:";
getline(cin, str);
}
// Overload the + operator to concatenatetwo strings
ConcatenateStrings operator+(constConcatenateStrings& obj) {
ConcatenateStrings temp;
temp.str = this->str + obj.str; // Concatenation of two strings
return temp;
}
// Function to display the concatenatedstring
void display() const {
cout << "Concatenatedstring: " << str << endl;
}
};
intmain() {
ConcatenateStrings str1, str2, result;
// Get two strings from the user
str1.getData();
str2.getData();
// Use the overloaded + operator toconcatenate the strings
result = str1 + str2;
// Display the result
result.display();
return 0;
}
Outut:
Entera string: Hello
Entera string: World
Concatenatedstring: HelloWorld