#include <iostream>#include <string>using namespace std;class A { int a; public: A(int i) { a = i; } void assign(int i) { a = i; } int getA() { return a; }};int main() { A obj; obj.assign(5); cout << obj.getA();}
Question
#include <iostream>#include <string>using namespace std;class A { int a; public: A(int i) { a = i; } void assign(int i) { a = i; } int getA() { return a; }};int main() { A obj; obj.assign(5); cout << obj.getA();}
Solution
The code you've provided is written in C++, but it contains an error. The class A has a constructor that requires an integer argument, but in your main function, you're trying to create an instance of A without providing any arguments.
Here's how you can fix it:
#include <iostream>
#include <string>
using namespace std;
class A {
int a;
public:
A(int i) {
a = i;
}
void assign(int i) {
a = i;
}
int getA() {
return a;
}
};
int main() {
A obj(0); // Provide an initial value for 'a'
obj.assign(5);
cout << obj.getA();
}
In this corrected version, I've initialized obj with a value of 0. Then, obj.assign(5) changes the value of a to 5, and cout << obj.getA() prints 5 to the console.
Similar Questions
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.