Oop Unit Iv
Oop Unit Iv
1. Function Prototype Matching: The prototype (including return type, name, and 1M
each
parameter list) of a virtual function must be identical in the base class and all
(Any
derived classes that override it. This ensures that the compiler can identify the 2
corre
function correctly even when using a base class pointer or reference.
ct
2. Access through Base Class Pointer or Reference: Virtual functions are typically Rule
s)
accessed through pointers or references of the base class type. This allows for
runtime polymorphism, where the actual function called depends on the object's
dynamic type at runtime, not the pointer or reference type.
3. Declaration: Virtual functions are declared using the virtual keyword in the base
class.
4. Member Function: Virtual functions must be member functions of a class. They
cannot be static members.
5. Access through Pointers or References: Virtual functions are typically accessed
through pointers or references of the base class type. This enables runtime
polymorphism, where the specific function to be called is determined at runtime
based on the actual object type.
6. Optional Override: A derived class can optionally choose to override
(redefine) the behavior of an inherited virtual function. This allows for
specialization of the function in the derived class.
RSCOEP Department of Computer Engineering Prof S.U.Puri 129
7. Base Class Definition: A virtual function must be defined (have a body) in the
base class, even if it's not overridden in any derived classes.
8. Friend Functions: Virtual functions can be declared as friend functions of
another class. This allows the friend function to access the virtual function directly,
even if it's called through a base class pointer.
9. No Virtual Constructors: Class cannot have virtual constructors, but can have
virtual destructors.
2. Explain virtual function with suitable example.Give the rules of virtual 4 S-24
function.
Virtual Function:
A virtual function (also known as virtual methods) is a member function that is
declared within a base class and is re-defined (overridden) by a derived class.
When you refer to a derived class object using a pointer or a reference to the base
class, you can call a virtual function for that object and execute the derived class’s
version of the method.
Example:
#include<iostream>
using namespace std;
class base
{
public:
virtual void print()
{
cout << "print base class\n";
}
void show()
{
cout << "show base class\n";
}
};
class derived : public base
{
public:
void print()
{
cout << "print derived class\n";
}
void show()
{
cout << "show derived class\n";
}
};
int main()
{
base* bptr;
derived d;
RSCOEP Department of Computer Engineering Prof S.U.Puri 130
bptr = &d;
bptr->print();
bptr->show();
}
Function Overloading
Function overloading allows multiple functions to have the same name within the
same scope, as long as their parameter lists are different. This is a form of compile-
time polymorphism.
#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "Sum of integers: " << a + b << endl;
}
void add(double a, double b) {
cout << "Sum of doubles: " << a + b << endl;
}
int main() {
Example:
C++
Example:
C++
int x = 10;int *ptr = &x;int y = *ptr; // y now holds the value of x, which is 10
In this example, *ptr dereferences the pointer ptr to get the value at the address it
points to (which is the value of x).
The this pointer is a special constant pointer available within the non-static
member functions of a class. It points to the object whose member function is
being called.
How it works:
When an object calls a non-static member function, the compiler implicitly passes
a hidden argument to the function: a pointer to that object itself.
You can use this to access the object's members from within its own member
functions.
#include <iostream>
class MyClass {
public:
int x;
void print() {
};
MyClass obj;
obj.setX(10);
obj.print();
return 0;
Explanation:
In the setX function, this->x is equivalent to x. However, using this explicitly can
be helpful when there's a name conflict between a member variable and a local
variable.
The print function demonstrates how to access and print the object's data member
using this.
It can be used to access the object's members and return a reference to the object
itself.
It's often used in constructors, operator overloading, and when there's a name
conflict between a member and a local variable.
Cannot be static: Static members belong to the class, not objects, so they can't
be overridden.
Can be a friend of another class: This doesn't affect their virtual behavior.
Must be defined in the base class: Even if not used, a virtual function must
have a definition in the base class.
Prototype must match: The prototype (return type, name, and parameters) of a
virtual function must be identical in both base and derived classes.
#include <iostream>
class Base {
public:
};
public:
};
int main() {
delete basePtr;
return 0;
10. Write a program to declare a class ‘item’ containing data members as 6 W-23
‘item_name’, ‘code’, ‘price’. Accept and display the information for one
RSCOEP Department of Computer Engineering Prof S.U.Puri 139
object using pointer to that object.
#include <iostream>
#include <string>
class Item {
public:
string item_name;
int code;
double price;
};
int main() {
Item item;
getline(cin, ptr->item_name);
return 0;
Types of Polymorphism
Efficiency
Direct memory access: Pointers provide direct access to memory locations, which
can lead to faster program execution compared to accessing data through variables.
Flexibility
Low-level programming
System programming: Pointers are crucial for operating system development and
other system-level programming.
13. Write C++ program to overload binary operator ‘+’ to concatenate two 6 S-23
strings.
#include <iostream>
#include <string>
class String {
string str;
void display() {
};
int main() {
String s1("Hello");
String s3 = s1 + s2;
s3.display();
return 0;
A pointer in C++ is a variable that stores the memory address of another variable.
It acts like a locator or indicator pointing to the location where data is stored.
16. Develop a c++ program to perform arithmetic operation using pointer. 4 W-22
#include <iostream>
using namespace std;
int main() {
int num1 = 10, num2 = 20;
int *ptr1 = &num1, *ptr2 = &num2;
// Addition
int sum = *ptr1 + *ptr2;
cout << "Sum: " << sum << endl;
// Subtraction
int difference = *ptr1 - *ptr2;
cout << "Difference: " << difference << endl;
// Multiplication
int product = *ptr1 * *ptr2;
RSCOEP Department of Computer Engineering Prof S.U.Puri 143
cout << "Product: " << product << endl;
// Division
if (*ptr2 != 0) {
double quotient = static_cast<double>(*ptr1) / *ptr2;
cout << "Quotient: " << quotient << endl;
} else {
cout << "Division by zero error!" << endl;
}
return 0;
}
17. Explain rules of operator overloading and overload ‘+’ operator to 6 W-22
concatenate two string.
Operator Overloading
Operator overloading is a feature in C++ that allows you to redefine the behavior
of built-in operators for user-defined data types. This enhances code readability
and expressiveness.
Rules of Operator Overloading
Only built-in operators can be overloaded.
The arity of the operator cannot be changed. For instance, you cannot make a
unary operator binary or vice versa.
Operator precedence and associativity cannot be changed.
Overloaded operators follow the same rules of precedence and associativity as
their built-in counterparts.
Overloaded operators cannot be new operators. They must have existing
definitions.
The return type of an overloaded operator should be intuitive. For example,
overloading + for string concatenation should return a string.
Overloading the + Operator for String Concatenation
#include <iostream>
#include <string>
using namespace std;
class String {
public:
string str;
RSCOEP Department of Computer Engineering Prof S.U.Puri 144
String(const string& s) : str(s) {}
String operator+(const String& other) {
return String(str + other.str);
}
void display() {
cout << str << endl;
}
};
int main() {
String s1("Hello");
String s2(" World");
String s3 = s1 + s2;
s3.display();
return 0;
}
18. Develop c++ program to implement inheritance shown in fig. 6 W-22
#include <iostream>
using namespace std;
class HOD {
public:
virtual void display() {
cout << "HOD" << endl;
}
};
class Faculty : public HOD {
Virtual functions are essential for achieving runtime polymorphism in C++. This
means that the decision about which function to call is made at runtime based on
the actual type of the object, rather than the declared type of the pointer or
reference.
Runtime polymorphism: Allows for different behaviors based on the object's type
at runtime.
Base class pointers: Enables using a base class pointer to refer to objects of derived
classes and calling appropriate functions.
Generic programming: Facilitates writing generic code that can work with different
derived classes.
Design patterns: Supports design patterns like Template Method, Strategy, and
Observer.
20. Write a C++ program to overload add function to add two integer numbers 4 S-22
and two float numbers.
#include <iostream>
return a + b;
return a + b;
int main() {
cout << "Sum of integers: " << add(num1, num2) << endl;
cout << "Sum of floats: " << add(f1, f2) << endl;
return 0;
21. i) Define pointer operator and address operator with example. 6 S-22
ii) Write a C++ program to declare a class train with members as train no and
name. Accept and display data for one object of train. Use pointer to object to
call functions of class
#include <iostream>
int main() {
int x = 10;
The address operator, denoted by &, returns the memory address of a variable.
#include <iostream>
int main() {
int x = 10;
int *ptr = &x; // ptr stores the address of x using the address operator
return 0; }
ii) Write a C++ program to declare a class train with members as train no and
name. Accept and display data for one object of train. Use pointer to object to
call functions of class
#include <iostream>
#include <string>
class Train {
public:
int train_no;
string name;
void acceptData() {
getline(cin, name);
void displayData() {
};
int main() {
Train train;
ptr->acceptData();
ptr->displayData();
return 0;
22. Write a C++ program to overload “+” operator so that it will perform 6 S-22
concatenation of two strings. (Use class get data function to accept two strings)
#include <iostream>
#include <string>
class String {
public:
string str;
void getData() {
getline(cin, str);
String temp;
return temp;
void display() {
};
int main() {
s1.getData();
s2.getData();
s3 = s1 + s2;
s3.display();
return 0;
‘this’ pointer:
C++ uses a unique keyword called „this‟ to represent an object that invokes a
member function. This unique pointer is automatically passed to a member
function when it is invoked. „this‟ is a pointer that always point to the object for
which the member function was called.
For example, the function call A.max ( ) will set the pointer „this‟ to
the address of the object A. Then suppose we call B.max ( ), the pointer „this‟ will
store address of object B.
Example:
#include<iostream.h>
class sample
public:
void setdata(int x)
this ->a=x;
void putdata()
cout<<this ->a;
};
void main()
sample s;
s.setdata(100);
s.putdata( );
24. Write a program to declare a class ‘book’ containing data members as ‘title’, 6 W-19
‘author-name’, ‘publication’, ‘price’. Accept and display the information for
one object using pointer to that object.
#include<iostream.h>
#include<conio.h>
class book
char author_name[20];
char publication[20];
float price;
public:
void Accept();
void Display();
};
void book::Accept()
void student::Display()
price<<”\n”<<;
void main()
book b, *p;
clrscr();
p=&b;
p->Accept();
p-> Display();
getch();
25. Write a program to overload the ‘—’ unary operator to negate the values. 6 W-19
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Number
int x,y;
public:
a =x;
b =y;
void display()
void operator - ( )
x = - x;
y = - y;
};
void main ()
clrscr ();
-N1;
getch ();
int *ptr, a = 5;
ptr = & a;
variable a in ptr)
cout<< * ptr;
value 5.
cout<< (* ptr) + 1;
displays value 6
(ii) Write a program in C++ to overload unary ‘_’ operator to negate values
of data members of class.
be created.
4. Overloaded operators follow the syntax rules of the original operators. They
can’t be overridden.
explicit arguments and return no explicit values, but, those overloaded by means
of the friend function, take one reference argument (the object of the relevant
class).
9. When using binary operators overloaded through a member function, the left
hand operand must be an object of the relevant class.
Return a value. They must not attempt to change their own arguments.
(ii) Write a program in C++ to overload unary ‘_’ operator to negate values of
data members of class.
#include<iostream.h>
#include<conio.h>
#include<string.h>
int x, y;
public:
a =x;
b =y;
void display()
void operator - ( )
x = - x;
y = - y;
};
void main()
Number N1(5,6);
clrscr();
N1.display();
-N1;
getch();
28. With suitable example, describe effect of ++ and – – operators used with 4 W-18
pointer in pointer arithmetic.
increment with respect to size of the data type used to declare pointer
variable.
Example:-
int a[5]={10,20,30,40,50},*ptr;
ptr=a[0];
for(i=0;i<5;i++)
cout<<*ptr;
ptr++;
pointer decrement with respect to size of the data type used to declare
pointer variable.
29. Write a C++ program to swap two integer numbers and swap two float 4 W-18
#include<iostream.h>
#include<conio.h>
int temp;
temp=a;
a=b;
b=temp;
float temp1=x;
x=y;
y=temp1;
void main()
clrscr();
swap(10,20);
swap(10.15f,20.25f);
getch();
30. Write a C++ program to overload binary operator ‘+’ to concatenate two 6 W-18
strings.
#include<conio.h>
#include<string.h>
class opov
char str1[10];
public:
void getdata()
cout<<"\nEnter a strings";
cin>>str1;
cout<<strcat(str1,o.str1);
};
void main()
opov o1,o2;
clrscr();
o1.getdata();
o2.getdata();
o1+o2;
getch();