Question

I'm sorry if this has been asked already, but I'm still learning C++ and struggling with a bit of syntax.

I'm supposed to overload the type conversion operator, so that it will accept an object and return an int value, based on a protected int inside that object.

Header file:

definitions.h

class Baseballs 
{
protected:
    int currentValue;
public:
    Baseballs(int);
    int operator= (Baseballs&); // ??????
}

Methods:

methods.cpp

#include "definitions.h"

Baseballs::Baseballs(int value)
    {
    currentValue = value;
    }

int Baseballs::operator=(Baseballs &obj) // ??????
    { 
        int temp = obj.currentValue;
        return temp; 
    } 

So in main.cpp, if I create an object:

Baseballs order(500);

Then 500 is assigned to currentValue. I need to be able to assign that to an int variable, and ultimately print it for verification, such as:

int n = order;
cout << n;

What I'm having trouble with is the syntax for overloading =. Can someone tell me what the proper syntax for the definition and method should be?

Was it helpful?

Solution

The overloaded = is really to assign to objects of the same type. Ex:

order = another_order;

What you are looking for is an overloaded conversion operator.

operator int() { return currentvalue; }

However this is generally not regarded as good practice, due to unknown conversions. An explicit overload is much safer:

explicit operator int() {...}

However you would need to do:

int n = static_cast<int>(order);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top