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]


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]

Join a list of 2000+ Programmers for latest Tips & Tutorials