You are on page 1of 4

1. What is Single Inheritance?

Ans, single inheritance is when a new class (child) inherits characteristics from just
one existing class (parent). It's like a child inheriting traits from a single parent,
allowing for the sharing and extension of attributes and behaviours.

2.example- single

#include <iostream>
using namespace std;

class A {
public:
int subtract(int a, int b) {
return a - b;
}
};

class S : public A {
public:
void performSubtraction(int a, int b) {
int result = subtract(a, b);
cout << a << " - " << b << " = " << result << endl;
}
};

int main() {
S sObj;

sObj.performSubtraction(10, 5);

return 0;
}

3.example- multiple

#include <iostream>

using namespace std;

class Addition {
public:
int add(int a, int b) {
return a + b;
}
};

class Subtraction {
public:
int subtract(int a, int b) {
return a - b;
}
};

class MathOperation : public Addition, public Subtraction {


public:
void performOperations(int a, int b) {
int sum = add(a, b);
int difference = subtract(a, b);
cout << a << " + " << b << " = " << sum << endl;
cout << a << " - " << b << " = " << difference << endl;
}
};

int main() {
MathOperation mathObj;

mathObj.performOperations(10, 5);

return 0;
}

4.What is Multiple Inheritance?

Ans,In simple terms, is when a new class inherits characteristics from two or more
existing classes. It's like a child inheriting traits from multiple parents, allowing it to
combine and use features from different sources. This can make code more flexible
but also more complex to manage.
5.What is Multilevel Inheritance?

Ans,In simple terms, is when you have a chain of classes, where each class inherits
from the one above it. It's like a family tree where a grandchild inherits traits from a
parent and a grandparent. This creates a hierarchy of classes, with each level
building upon the one before it.

6,example- Multilevel

#include <iostream>

using namespace std; // This line allows you to use elements from the std
namespace without the 'std::'

class MathOperation {
public:
int multiply(int a, int b) {
return a * b;
}
};

class Addition : public MathOperation {


public:
int add(int a, int b) {
return a + b;
}
};

class Subtraction : public Addition {


public:
int subtract(int a, int b) {
return a - b;
}
};

int main() {
Subtraction operation;

int a = 10, b = 5;
int result_addition = operation.add(a, b);
int result_subtraction = operation.subtract(a, b);
cout << a << " + " << b << " = " << result_addition << endl; // Output: "10 + 5 = 15"
cout << a << " - " << b << " = " << result_subtraction << endl; // Output: "10 - 5 = 5"

return 0;
}

You might also like