Single and Multiple Inheritance
Single and Multiple 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>
// Base class
class Animal {
public:
void makeSound() {
};
// Derived class
public:
};
int main() {
Dog myDog;
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>
class Person {
protected:
string name;
public:
Person(string n) {
name = n;
void showName() {
};
private:
int rollNo;
public:
rollNo = r;
void showDetails() {
showName();
};
int main() {
s1.showDetails();
return 0;
Output:
Name: Alice
Create two base classes, Engine and Wheels, and a derived class Car that inherits from both.
Solution:
#include <iostream>
// Base class 1
class Engine {
public:
void startEngine() {
};
// Base class 2
class Wheels {
public:
void rollWheels() {
};
// Derived class
public:
void drive() {
startEngine();
rollWheels();
};
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>
class A {
public:
void show() {
};
class B {
public:
void show() {
};
public:
void show() {
B::show();
};
int main() {
C obj;
obj.show();
return 0;
Output:
Class A Show
Class B Show