C++ Solutions for Questions 7(c) to 10(c)
7(c) Increment Operator Overloading using Member Function
#include <iostream>
using namespace std;
class Count {
int value;
public:
Count() : value(0) {}
void display() { cout << "Value: " << value << endl; }
Count operator++() {
++value;
return *this;
}
};
int main() {
Count c;
++c;
[Link]();
return 0;
}
8(a) Increment Operator Overloading using Friend Function
#include <iostream>
using namespace std;
class Count {
int value;
public:
Count() : value(0) {}
void display() { cout << "Value: " << value << endl; }
friend Count operator++(Count&);
};
Count operator++(Count& c) {
++[Link];
return c;
}
int main() {
Count c;
++c;
[Link]();
return 0;
}
8(b) Complex Number Addition using Operator Overloading
#include <iostream>
using namespace std;
class Complex {
float real, imag;
public:
void input() {
cout << "Enter real and imaginary part: ";
cin >> real >> imag;
}
Complex operator+(Complex c) {
Complex temp;
[Link] = real + [Link];
[Link] = imag + [Link];
return temp;
}
void display() {
cout << "Sum: " << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1, c2, result;
[Link]();
[Link]();
result = c1 + c2;
[Link]();
return 0;
}
8(c) Binary Operator Arguments
A binary operator requires two arguments. As a member function, it takes one argument
(right-hand side). As a friend function, it takes two arguments.
9(a) Public vs Private Derivation
Public derivation keeps base public/protected members as is. Private derivation makes
them private in the derived class.
9(b) Inheriting Private Members
Private members can't be accessed directly. Use 'protected' or getter/setter.
class Base {
private:
int data;
protected:
int getData() { return data; }
};
class Derived : public Base {
public:
void showData() {
cout << "Accessing through protected: " << getData() << endl;
}
};
9(c) Ambiguity in Multiple Inheritance
Ambiguity arises when two base classes have the same member.
class A { public: void show() { cout << "A\n"; } };
class B { public: void show() { cout << "B\n"; } };
class C : public A, public B {
public:
void display() {
A::show(); // Resolves ambiguity
B::show();
}
};
10(a)(b)(c) Student, Test, Result Classes
#include <iostream>
using namespace std;
class Student {
protected:
string name;
int roll;
public:
void inputStudent() {
cout << "Enter name and roll number: ";
cin >> name >> roll;
}
};
class Test : public Student {
protected:
int marks[3];
public:
void inputMarks() {
cout << "Enter marks for 3 subjects: ";
for (int i = 0; i < 3; ++i)
cin >> marks[i];
}
};
class Result : public Test {
int total;
public:
void display() {
total = 0;
for (int i = 0; i < 3; ++i)
total += marks[i];
cout << "\nName: " << name << "\nRoll No: " << roll << "\nTotal Marks: " <<
total << endl;
}
};
int main() {
Result r;
[Link]();
[Link]();
[Link]();
return 0;
}