Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Header File Content Puzzle [Interview Question]

Tags:

c++

puzzle

What should be the content of the header file Fill.hpp such that the following code works i.e both asserts work?

#include <iostream>
#include <string>
#include <cassert>
#include "Fill.hpp"

int main() 
{
  std::string s = multiply(7,6);
  int i = multiply(7,6);
  assert(s == "42");
  assert(i == 42);
}

TIA

like image 764
McCutcheon Jr Avatar asked Apr 25 '11 15:04

McCutcheon Jr


People also ask

Which header file must be included in a code to use file function?

In C++ program has the header file which stands for input and output stream used to take input with the help of “cin” and “cout” respectively. There are of 2 types of header file: Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them.

What is the use of header file?

Why Do You Use Header Files? Header files are used in C++ so that you don't have to write the code for every single thing. It helps to reduce the complexity and number of lines of code. It also gives you the benefit of reusing the functions that are declared in header files to different .


1 Answers

Define conversion functions for converting a type multiply into int and std::string as shown in Method 1 or use Method 2 (similar to 1)

Method 1

struct multiply
{  
    int t1,t2;
    operator std::string()
    {
        std::stringstream k;
        k<<(t1*t2);
        return k.str();
    }
    operator int()
    {   
        return t1*t2;
    }
    multiply(int x, int y):t1(x),t2(y){}
};

Method 2

class PS
{
  int _value;
  public:
  PS(int value) : _value(value) {}    
  operator std::string() 
  {
    std::ostringstream oss;
    oss << _value;
    return oss.str();
  }    
  operator int() 
  {
    return _value;
  }
};

PS multiply(int a, int b) 
{
  return PS(a * b);
}
like image 57
Prasoon Saurav Avatar answered Oct 21 '22 04:10

Prasoon Saurav