60.2 Practice - Sorting By Size (Member Initializers) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

60.2 Practice - Sorting By Size (Member Initializers)

You are making a program to store TVs with their width and height. The given program declares a TV class with height and width members, an area() method, as well as a constructor that initializes the members of the class. Complete the program by taking 2 integers as input, create a TV object by passing them to the constructor, and call the area() method. *Note, that the constructor needs 2 integer values. My code is below based on the lesson but it doesn’t work. Please help.

25th Dec 2021, 12:43 AM
Chin Eu
Chin Eu - avatar
4 Answers
+ 3
#include <iostream> using namespace std; class TV { public: TV(int h, int w): height(h), width(w) {}; void area() { cout <<height*width; } private: int height; int width; }; int main() { //your code goes here int x, y; cin >> x >> y; TV o(x, y); o.area(); }
4th Aug 2022, 2:14 PM
Neal
+ 2
A few observations: You need to make 1 TV object. - You are making 2, 1 called height and another called weight and you're not using either of these objects. TV requires 2 integers in order to construct one. - You are passing 1 string to both. Use cin to get user input if the program requires it. The member function, area, for the TV takes 0 arguments. - You are passing 1, the product of 2 non-existing variables. In order to call a member function you need to tell the code on which object to call it on. - You are currently treating area as a freestanding function. area returns void, meaning nothing. So you cannot use it with cout in this case. area already prints it on its own. Review the tutorial if you need to, these are covered topics.
25th Dec 2021, 8:45 AM
Dennis
Dennis - avatar
+ 1
Thanks Dennis for the lengthy explanation. Finally manage to solve it.
25th Dec 2021, 2:46 PM
Chin Eu
Chin Eu - avatar
- 1
#include <iostream> using namespace std; class TV { public: TV(int h, int w): height(h), width(w) {}; void area() { cout <<height*width; } private: int height; int width; }; int main() { //your code goes here TV height("h"); TV weight("w"); cout << area(h*w); }
25th Dec 2021, 7:19 AM
Chin Eu
Chin Eu - avatar