Practice Sheet OOPs-2
Practice Sheet OOPs-2
Page 1 of 5
Programming Sheet-2 (OOPs)
3. Inline Functions
Task: Create a C++ program to define an inline functions.
#include <iostream>
using namespace std;
inline int square(int x) {
return x * x;
}
int main() {
cout << "Square of 5: " << square(5) << endl;
cout << "Square of 8: " << square(8) << endl;
return 0;
}
4. Function Overloading
Task: Explain the concept of function overloading using a C++ program.
#include <iostream>
using namespace std;
void display(int x) {
cout << "Integer: " << x << endl;
}
void display(double x) {
cout << "Double: " << x << endl;
}
void display(string x) {
cout << "String: " << x << endl;
}
int main() {
display(10);
display(3.14);
display("Hello");
return 0;
}
Page 2 of 5
Programming Sheet-2 (OOPs)
int main() {
greet(); // default argument will be used
greet("Alice");
return 0;
}
7. Friend Function
Task: WAP to explain how a friend function can access the private members of the class
#include <iostream>
using namespace std;
class Box {
int width;
public:
Box() : width(10) {}
friend void printWidth(Box box); // Friend function declaration
};
Page 3 of 5
Programming Sheet-2 (OOPs)
8. Friend Class
Task: WAP for friend class.
#include <iostream>
using namespace std;
class B;
class A {
int data;
public:
A() : data(10) {}
friend class B; // Declaring friend class
};
class B {
public:
void display(A &obj) {
cout << "Value of A's data: " << obj.data << endl; // Access private data
}
};
int main() {
A a;
B b;
b.display(a);
return 0;
}
Page 4 of 5
Programming Sheet-2 (OOPs)
string name;
public:
Student(string name) {
this->name = name; // Using 'this' pointer to refer to class member
}
void display() {
cout << "Student's name: " << this->name << endl;
}
};
int main() {
Student s("John");
s.display();
return 0;
}
Page 5 of 5