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:
Frequently Asked:
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:
Best Resources to Learn C++:
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]