Tom a fellow Aggie wrote the following class class Box priv

Tom, a fellow Aggie, wrote the following class:

class Box {

private:

    int num;

    void set_num(int val) {

        num = val;

    }

public:

    Box() {

        num = 0;

    }

    Box(int val) {

        num = val;

    }

    int get_num() {

        return num;

    }

};

int main(void) {

    Box box(1);

    int val = box.get_num();

    box.set_num(val + 1);

}

Tom tried running the above code but it did not compile. What is wrong with Tom’s code, and how do you fix it?

Solution

solution.cpp

#include <iostream>//header for input output function
using namespace std;//it tells the compiler to link std namespace
class Box {
public:
int num;
void set_num(int val) {
num = val;
cout<<num;
}
public:
Box() {//constructor
num = 0;
}

Box(int val) {//constructor with argumens
num = val;
}

int get_num() {
return num;
}
};

int main(void) {//main function
Box box(1);
int val = box.get_num();
box.set_num(val + 1);
}

output

2

Tom, a fellow Aggie, wrote the following class: class Box { private: int num; void set_num(int val) { num = val; } public: Box() { num = 0; } Box(int val) { num
Tom, a fellow Aggie, wrote the following class: class Box { private: int num; void set_num(int val) { num = val; } public: Box() { num = 0; } Box(int val) { num

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site