VVG
VVG

Reputation: 141

Conversion constructor between classes c++

The background: I am reading a wonderful book, where they briefly mentioned conversion constructors.

Though I understand fundamentals of the conversion constructors, I was a bit lost, when in practice problems section they asked:

Write a conversion constractor that converts ratnum into realnum from the code that I received prior to the problem:

class ratnum {
    int num, denom;
public:
    ratnum(int numenator = 2, int denominator = 3) : num(numenator), denom(denominator) {}
    void show() { cout << static_cast<double>(num) / denom << endl; }
    double result() { return num / denom; }

};

class realnum {
    int number;
public:
    realnum(double numr = 0) : number (numr) {}
};  

I always dealt with the conversion constructors as such:

ratnum one = 10; //or
ratnum two = {10, 2}

But never saw that we can convert from class to a class type. Could you, please, say how such conversion constructor should work (maybe with example)?

Is defining a function result of the ratnum class and writing:

realnum check = one.result();

is what is meant here?

Upvotes: 0

Views: 301

Answers (2)

Puppy
Puppy

Reputation: 146910

But never saw that we can convert from class to a class type. Could you, please, say how such conversion constructor should work (maybe with example)?

It's exactly the same as converting from a non-class type. There's literally absolutely no difference at all.

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

I assume what they meant is that there is an overload of the constructor that takes an input of the other class, for example

realnum(ratnum const& other) : number{other.result()} {}

And vice-versa to construct a ratnum from a realnum, although that could be less trivial as there are irrational numbers, infinitely repeating numbers, etc.

You could use this version of the constructor to do something like

ratnum a{2, 4};
realnum b{a};    // This used your "conversion" constructor

Upvotes: 1

Related Questions