#include <iostream>
#include <stdexcept>

// Base class
class Base {
public:
    virtual void swap(Base* other) = 0; // Virtual function for swapping
};

// Derived class 1
class ClassA : public Base {
private:
    int dataA;

public:
    ClassA(int a) : dataA(a) {}

    void swap(Base* other) override {
        ClassA* objA = dynamic_cast<ClassA*>(other);
        if (objA) {
            std::swap(dataA, objA->dataA);
            std::cout << "Swapped objects of ClassA successfully." << std::endl;
        } else {
            throw std::invalid_argument("Cannot swap different types of objects.");
        }
    }

    void displayData() const {
        std::cout << "Data in ClassA: " << dataA << std::endl;
    }
};

// Derived class 2
class ClassB : public Base {
private:
    double dataB;

public:
    ClassB(double b) : dataB(b) {}

    void swap(Base* other) override {
        ClassB* objB = dynamic_cast<ClassB*>(other);
        if (objB) {
            std::swap(dataB, objB->dataB);
            std::cout << "Swapped objects of ClassB successfully." << std::endl;
        } else {
            throw std::invalid_argument("Cannot swap different types of objects.");
        }
    }

    void displayData() const {
        std::cout << "Data in ClassB: " << dataB << std::endl;
    }
};

int main() {
    try {
        ClassA objA(10);
        ClassB objB(3.14);

        objA.displayData(); // Display initial data in objA
        objB.displayData(); // Display initial data in objB

        objA.swap(&objB); // Attempt swapping between objects of different classes

        objA.displayData(); // Display data in objA after the attempted swapping
        objB.displayData(); // Display data in objB after the attempted swapping
    } catch (std::invalid_argument& ex) {
        std::cout << "Exception caught: " << ex.what() << std::endl;
    }

    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: