BCA 2nd Semester - C++ OOPs Practical File
1. Class and Object
Program Description:
This program demonstrates class and object.
Code:
#include <iostream>
using namespace std;
class Student {
public:
string name;
int roll;
void input() {
cout << "Enter name: ";
cin >> name;
cout << "Enter roll number: ";
cin >> roll;
}
void display() {
cout << "Name: " << name << ", Roll: " << roll << endl;
}
};
int main() {
Student s;
s.input();
s.display();
return 0;
}
Sample Output:
Enter name: Alice
Enter roll number: 101
Name: Alice, Roll: 101
Page 1
BCA 2nd Semester - C++ OOPs Practical File
2. Constructor and Destructor
Program Description:
This program demonstrates constructor and destructor.
Code:
#include <iostream>
using namespace std;
class Demo {
public:
Demo() {
cout << "Constructor called." << endl;
}
~Demo() {
cout << "Destructor called." << endl;
}
};
int main() {
Demo d;
return 0;
}
Sample Output:
Constructor called.
Destructor called.
Page 2
BCA 2nd Semester - C++ OOPs Practical File
3. Function Overloading
Program Description:
This program demonstrates function overloading.
Code:
#include <iostream>
using namespace std;
class Print {
public:
void display(int a) {
cout << "Integer: " << a << endl;
}
void display(double a) {
cout << "Double: " << a << endl;
}
void display(string a) {
cout << "String: " << a << endl;
}
};
int main() {
Print p;
p.display(5);
p.display(3.14);
p.display("Hello");
return 0;
}
Sample Output:
Integer: 5
Double: 3.14
String: Hello
Page 3
BCA 2nd Semester - C++ OOPs Practical File
4. Operator Overloading (Unary -)
Program Description:
This program demonstrates operator overloading (unary -).
Code:
#include <iostream>
using namespace std;
class Number {
int x;
public:
Number(int val) : x(val) {}
void operator-() {
x = -x;
}
void display() {
cout << "Value: " << x << endl;
}
};
int main() {
Number n(10);
-n;
n.display();
return 0;
}
Sample Output:
Value: -10
Page 4
BCA 2nd Semester - C++ OOPs Practical File
5. Calculator Class
Program Description:
This program demonstrates calculator class.
Code:
#include <iostream>
using namespace std;
class Calculator {
float a, b;
public:
void get() {
cout << "Enter two numbers: ";
cin >> a >> b;
}
void operations() {
cout << "Add: " << a + b << endl;
cout << "Sub: " << a - b << endl;
cout << "Mul: " << a * b << endl;
if (b != 0)
cout << "Div: " << a / b << endl;
else
cout << "Division by zero not allowed" << endl;
}
};
int main() {
Calculator c;
c.get();
c.operations();
return 0;
}
Sample Output:
Enter two numbers: 10 5
Add: 15
Sub: 5
Mul: 50
Div: 2
Page 5