| What is the output of the following C++ program? #include <iostream> class A { public: A(int i) : m_i(i) { } public: int operator()(int i = 0) const { return m_i + i; } operator int () const { return m_i; } private: int m_i; friend int g(const A&); }; int f(char c) { return c; } int g(const A& a) { return a.m_i; } int main() { A f(2), g(3); std::cout << f(1) << g(f) << std::endl; return 0; } |
Answer: 35 |
|
|
friend int g(const A&); as it isn't used. |
|
operator int() for f returns 2 because the functions in line 21 are excecuted BEFORE the functions in line 20. Which function is excecuted first is not specified in the C++ standard.
std::cout << f(1) << g(f) << std::endl; and not the functions f, g
int g(const A& a); in the global scope. You also have A g; in the local scope which will support g(f); through a few operator functions defined in the class. When an ambiguity exists, the compiler will generally take the local scope versions and give you a warning when you compile. |
|
a wasn't being set. This is a similar (and simplified) version of what we are explaining to you with the ambiguous function calls.
| Stewbond wrote: |
|---|
| because you're changing the value of f.m_i and using the value in two separate occurances in the same statement. |
const, that means that you can't modify the state of the object.| Shiva dzhee wrote: |
|---|
| const function is called for non-const object, |
| ne555 wrote: |
|---|
| "The methods are const, that means that you can't modify the state of the object." |