menu

arrow_back Can I use the same name to declare fields and methods of different classes?

by
1 vote
Is it possible to make fields with the same name but different values for different classes? (And also functions)

As I have to write now...#include using namespace std;class pyramid{private: int height1; int S;public: pyramid() :height1(0), S(0) {}; pyramid(int h1, int s) :height1(h1), S(s) {}; void display1() { cout << "--------Pyramid--------" << endl; cout << "Height: " << height1 << endl; cout << "Area of the base: " << S << endl; } float volume1() { return (height1 * S) / 3; }};class tr_pyramid{private: int height2; int S1; int S2;public: tr_pyramid() :height2(0), S1(0), S2(0) {}; tr_pyramid(int h2, int s1, int s2) :height2(h2), S1(s1), S2(s2) {}; void display2(int h, int s1, int s2) { cout << "---------Truncated pyramid--------" << endl; cout << "Height: " << h << endl; cout << "Area of the lower base: " << s1 << endl; cout << "Area of the upper base: " << s2 << endl; } float volume2(int h, int s1, int s2) { return h * (s1 + s2 + sqrt(s1 * s2)) / 3; }};int main(){ pyramid pr1(3, 27); //Значения объявил сам! (Сделано для разнообразия) tr_pyramid tr_pr1; int height, S1, S2; cout << "Enter the values of the truncated pyramid" << endl; cout << "Enter the height value: "; cin >> height; cout << "Enter the area of the lower base: "; cin >> S1; cout << "Enter the height of the top base: "; cin >> S2; cout << endl; pr1.display1(); cout << "Volume: " << pr1.volume1() << endl; cout << endl; tr_pr1.display2(height, S1, S2); cout << "Volume: " << tr_pr1.volume2(height, S1, S2) << endl; return 0;}

1 comment

Keep reading the textbook, don't be distracted by strange fantasies.

1 Answer

by
 
Best answer
0 votes
First, figure out what the scope is.
Answer: yes, you can.