Week 5
Week 5
#include <iostream>
using namespace std;
class Example {
int x;
public:
Example(int a) { x = a; }
void show() { cout << "Value: " << x << endl; }
};
int main() {
Example obj; // Error? Why?
obj.show();
return 0;
}
Ans The code will not run successfully due to the missing default constructor.
To fix it, either pass an argument to the constructor or define a default constructor.
#include <iostream>
using namespace std;
class BankAccount {
int accountNumber;
double balance;
public:
// Constructor Overloading
BankAccount(int accNum, double bal) {
accountNumber = accNum;
balance = bal;
}
int main() {
BankAccount acc1(101, 5000);
BankAccount acc2(102, 3000);
acc1.deposit(1500.50);
acc2.withdraw(500);
acc1.display();
acc2.display();
return 0;
}
3. Complete the following code to overload the << operator to print the object's value using cout.
#include <iostream>
using namespace std;
class Complex {
int real, imag;
public:
Complex(int r, int i) : real(r), imag(i) {}
// Overload << operator here
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4);
cout << c1; // Expected Output: 3 + 4i
return 0;
}
Demonstrate the ticket booking and cancellation process with multiple objects.
public:
Complex(int r, int i) : real(r), imag(i) {}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4);
cout << c1; // Expected Output: 3 + 4i
return 0;
}
This code demonstrates how to create multiple ticket objects, handle ticket bookings and
cancellations, and use static members to manage ticket IDs across different instances of the
Ticket class.
#include <iostream>
using namespace std;
class Car {
string model;
double pricePerDay;
bool isAvailable;
public:
// Default Constructor
Car() : model("Unknown"), pricePerDay(0.0), isAvailable(false) {}
// Parameterized Constructor
Car(string m, double price, bool available) : model(m), pricePerDay(price),
isAvailable(available) {}
// Copy Constructor
Car(const Car &c) : model(c.model), pricePerDay(c.pricePerDay), isAvailable(c.isAvailable) {}
int main() {
Car car1("Toyota", 50.0, true);
Car car2("BMW", 100.0, true);
car1.display();
car2.display();
return 0;
}