This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 28, 2023

Define pure virtual function and abstract class. Write a program to demonstrate ambiguity in multiple inheritance.

 A pure virtual function is a virtual function that has no implementation in the base class and is meant to be overridden by the derived class. It is declared by appending "= 0" to the function declaration in the base class. An abstract class is a class that contains at least one pure virtual function and cannot be instantiated, i.e., objects of an abstract class cannot be created.

Ambiguity in multiple inheritance occurs when a derived class inherits from multiple base classes that have member functions with the same name and signature. In such cases, the compiler may not know which version of the member function to use. To resolve this ambiguity, the derived class needs to specify which version of the member function to use by using the scope resolution operator (::).

Here's an example program that demonstrates ambiguity in multiple inheritance:

#include <iostream>
using namespace std;
class A {
public:
    void func() {
        cout << "Class A" << endl;
    }
};
class B {
public:
    void func() {
        cout << "Class B" << endl;
    }
};
class C : public A, public B {
public:
    // This function is required to resolve the ambiguity
    void func() {
        A::func();
    }
};
int main() {
    C obj;
    obj.func(); // Output: Class A
    return 0;
}

In this example, both classes A and B have a member function named "func()". When the class C inherits from both classes A and B, it also inherits both versions of "func()". To resolve the ambiguity, we define a new version of "func()" in class C that calls the version of "func()" from class A.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget