edmz
edmz

Reputation: 8494

Why isn't the conversion constructor called?

I've made a simple class just to try the conversion constructor in C++.

It works apparently, but when doing a certain operation, it seems that the compiler doesn't call it. I would know why, or maybe where I'm wrong.

#include <iostream>
using std::cout; using std::endl;

class CostruttoreConversione
{
public:  
  CostruttoreConversione(int val = 0)
  {
    cout << "Costruttore chiamato" << endl;
    valore = val;
  }

  inline int getValore(){
    return valore; 
  }

  CostruttoreConversione provaConversioneImplicita()
  {
    return -10; //here the type *should* be converted; doesn't happen.
  } 

private:
  int valore;
};

int main(void){
  CostruttoreConversione obj(10);
  cout << "obj = " << obj.getValore() << endl;
  obj = 20; //WORKS 
  cout << obj.getValore() << endl;
 // cout << obj.provaConversioneImplicita() << endl; doesn't work.
  return 0;
}

Upvotes: 0

Views: 103

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409176

The construction should work, but it's the output operation that fails because you haven't defined an output operator for your class.

You could still do e.g.

cout << obj.provaConversioneImplicita().getValore() << endl;

Or you define an output operator:

inline std::ostream& operator<<(std::ostream& os, const CostruttoreConversione& cc)
{
    os << cc.getValore();
    return os;
}

Upvotes: 2

Neel Basu
Neel Basu

Reputation: 12904

You can overload conversion operator so that CostruttoreConversione can convert to int.

class CostruttoreConversione{
  operator int() const{
     return valore;
  }
}

also write a copy constructor

Upvotes: 1

Avinash Kadimisetty
Avinash Kadimisetty

Reputation: 143

The default constructor and the parameterised constructor together constitute a conversion constructor. For example, If you are writing a program for creating an ADT array, when you declare a variable of data type array in the function main, main calls the parameterised constructor which is converting the array into the data type you used to develop array. So indirectly conversion is happening. Therefore the conversion constructor is not called. But the default and the parameterised constructor do the conversion internally.

Upvotes: 0

Related Questions