c++castingoperator-overloadingtypecasting-operatortypecast-operator

how to complete integer cast operator overload function signature here


Can someone please help me out with this question? I am unable to understand how to perform type cast overload here since typcast is not supposed to receive any arguments so naturally any attempts at giving it one fail too.

Fill in the blank at LINE-3 to complete integer cast operator overload function signature.

#include<iostream>
using namespace std;
class intString{
    int *arr;
    int n;
    public:
        intString(int k) : n(k){} //LINE-1
        int operator = (int n){ //LINE-2
            return arr[--n];
        }
        __________________(int &k){ //LINE-3
            int t;
            for(int j = 0; j < k; j++){
                cin >> t;
                this->arr[j] = t;
            }
            return *this;
        }
};
int main(){
    int k;
    cin >> k;
    intString s(k);
    s = k;
    for(int i = 0; i < k; i++)
        cout << static_cast<int>(s) << " ";
    return 0;
}

I have tried

operator int()(int&k){
.
.
.
}

and

operator int(int&k){
.
.
.
}

However, that obviously didn't work. I am really at a loss at what to do here.


Edit: Here is the question: Consider the following program with the following instructions.

Here is the code block unedited:

#include<iostream>
using namespace std;
class intString{
    int *arr;
    int n;
    public:
        intString(int k) : ______________________{} //LINE-1
        _______________{ //LINE-2
            return arr[--n];
        }
        __________________(int &k){ //LINE-3
            int t;
            for(int j = 0; j < k; j++){
                cin >> t;
                this->arr[j] = t;
            }
            return *this;
        }
};
int main(){
    int k;
    cin >> k;
    intString s(k);
    s = k;
    for(int i = 0; i < k; i++)
        cout << static_cast<int>(s) << " ";
    return 0;
}

Solution

  • After reading the code below // LINE 3, it seems like the question mixed up what line LINE 2 and LINE 3 are supposed to do. The block returns *this, which is an object of type intString, not an integer. Furthermore, user-defined type casts or type overloads like these don't allow a param to be passed to them, so k won't be defined in the scope of that method.

    Moreover, a look at the driver code suggests that the assignment s = k; should take some user input that sets the values in arr, which can then be fetched by the loop below. At LINE 2, n shouldn't be passed as it's a data member of the class...

    I think the question got flipped for LINE 2 and LINE 3.

    So, to sum up LINE 1, LINE 2 and LINE 3 should probably be -

    LINE-1:

    intString(int k) : n(k), arr(new int[k]) {

    LINE-2:

    operator int() {

    LINE-3:

    intString operator= (int &k) {

    I've purposefully left the above spoiler tagged, in case you want to solve this yourself.