0

C++ Some one explain for me this.

Which of the two is a good practice. But both programs can run. #include <iostream> using namespace std; class shape { public: int height; int width; void setwidth(int w) { width = w; } void setheight(int h) { height = h; } }; class rectangle: public shape { public: int getArea() { return(width*height); } }; int main() { rectangle rect; rect.setwidth(10); rect.setheight(5); cout <<"the area of the rectangle is: "<<rect.getArea(); } and why. here int height and int width are declared in the public Here are declared down in protected // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived class class Rectangle: public Shape { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total area: " << Rect.getArea() << endl; return 0; }

12th Apr 2019, 9:23 PM
Mugalu Manisuli
Mugalu Manisuli - avatar
2 Respostas
0
Mostly it makes more sense to declare variables in private / protected. Only declare them in public, if you have to access them from outside the class. Also it is good practice to not define the whole function in class definition and using constructors, when assigning variables at creation of the class. I would do it like in following example: https://code.sololearn.com/cu4Aoh5Fj43E
14th Apr 2019, 10:15 AM
Revox
Revox - avatar
0
#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 h,w; //taking input height and width cin>>h>>w; //Object calling constructor TV t(h,w); t.area(); } Good Luck
25th Jan 2022, 6:03 PM
Muhammad Alif Deva Rizqon
Muhammad Alif Deva Rizqon - avatar