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:

Advertisements

[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]

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

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

Scroll to Top