Question 1: Implement Single Inheritance
Create a base class Animal with a function makeSound(). Derive a class Dog from Animal and
override the function to print "Bark!".
Solution:
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
void makeSound() {
cout << "Some generic animal sound" << endl;
};
// Derived class
class Dog : public Animal {
public:
void makeSound() { // Overriding the function
cout << "Bark!" << endl;
};
int main() {
Dog myDog;
myDog.makeSound(); // Output: Bark!
return 0;
}
Question 2: Implement Single Inheritance with Constructor
Create a base class Person with a constructor that takes a name. Derive a class Student that
adds a roll number and displays both name and roll number.
Solution:
#include <iostream>
using namespace std;
class Person {
protected:
string name;
public:
Person(string n) {
name = n;
void showName() {
cout << "Name: " << name << endl;
};
class Student : public Person {
private:
int rollNo;
public:
Student(string n, int r) : Person(n) {
rollNo = r;
void showDetails() {
showName();
cout << "Roll No: " << rollNo << endl;
};
int main() {
Student s1("Alice", 101);
s1.showDetails();
return 0;
Output:
Name: Alice
Roll No: 101
Question 3: Implement Multiple Inheritance
Create two base classes, Engine and Wheels, and a derived class Car that inherits from both.
Solution:
#include <iostream>
using namespace std;
// Base class 1
class Engine {
public:
void startEngine() {
cout << "Engine started" << endl;
};
// Base class 2
class Wheels {
public:
void rollWheels() {
cout << "Wheels rolling" << endl;
};
// Derived class
class Car : public Engine, public Wheels {
public:
void drive() {
startEngine();
rollWheels();
cout << "Car is moving" << endl;
};
int main() {
Car myCar;
myCar.drive();
return 0;
Output:
Engine started
Wheels rolling
Car is moving
Question 4: Handling Ambiguity in Multiple Inheritance
Create two base classes A and B, both having a function show(). Derive a class C from A and
B, and resolve ambiguity using scope resolution.
Solution:
#include <iostream>
using namespace std;
class A {
public:
void show() {
cout << "Class A Show" << endl;
};
class B {
public:
void show() {
cout << "Class B Show" << endl;
};
class C : public A, public B {
public:
void show() {
A::show(); // Resolving ambiguity
B::show();
};
int main() {
C obj;
obj.show();
return 0;
Output:
Class A Show
Class B Show