boost::any questions

Question 1:

Will this code compile :

#include <iostream>
#include "boost/any.hpp"

class Node
{
private:
    int value;
   Node(const Node & obj)
    {

        value = obj.value;
    }
public:
    Node(int i)
    {
        value = i;
    }
};
int main()
{
    boost::any var1 = new Node(5);
    return 0;
}

Answer:

[code collapse=”true”]
Yes, because we are storing pointer in boost::any, not the object of Node Class and pointers are always copy constructible.
[/code]
[showads ad=inside_post]
Question 2:

Will this code compile :

#include <iostream>
#include "boost/any.hpp"

class Node
{
private:
    int value;
   Node(const Node & obj)
    {
        value = obj.value;
    }
public:
    Node(int i)
    {
        value = i;
    }
};
int main()
{
    boost::any var1 = Node(5);
    return 0;
}

Answer:

[code collapse=”true”]
Yes, because we are storing object of Node Class and its copy constructor is private. Therefore its object is not copy constructible and cannot be stored in boost::any.
[/code]

Question 3:

This code will throw exception or not ?

#include <iostream>
#include "boost/any.hpp"

int main()
{
    char c = '6';
    int i = c;
    boost::any var1 = c;
    std::cout << boost::any_cast<int> (x1) << std::endl;
    return 0;
}

Answer:

[code collapse=”true”]
Yes, it will throw boost::bad_any_cast exception because types are not matched exactly. It doesn’t do the automatic type conversion.
[/code]

Question 4:

This program will throw a run-time exception or not?

#include <iostream>
#include "boost/any.hpp"

class Base{};

class Derived : public Base {};

int main()
{
    Derived *dPtr = new Derived();
    boost::any dAny = dPtr;
    Base * bPtr = boost::any_cast<Base * >(dPtr);
    return 0;
}

Answer:

[code collapse=”true”]
Yes, it will throw boost::bad_any_cast exception because boost::any_cast is not able to understand polymorphism.
[/code]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top