This is a simple C program that I made, I'm only using classes and constructors on this code. The problem here is, if I print out one of the entity's attributes, C would give me a runtime error where it won't print out the entity's height, weight, material or place. It just prints nothing.
here's the code:
#include <iostream>
using namespace std;
class Monolith{
public:
int height;
int weight;
string material;
string place;
Monolith (int height, int weight, string material, string place){
height = height;
weight = weight;
material = material;
place = place;
}
};
int main()
{
Monolith EiffelTower(300, 10000, "Iron", "Paris");
cout << EiffelTower.place;
return 0;
}
CodePudding user response:
You're assigning nothing at all, because you assign to your local variables.
Either try:
Monolith (int height, int weight, string material, string place){
this->height = height;
this->weight = weight;
this->material = material;
this->place = place;
}
or this:
Monolith (int height, int weight, string material, string place) :
height(height),
weight(weight),
material(material),
place(place)
{
}
To elaborate on what's going wrong: The problem is 'variable scope'. 'Local' tops 'class', 'class' tops 'global', in this order.
So if you have local variables that have the same name as the class variables, you need to declare your 'target scope' explicitely (hence the this->
, which explicitely addresses the class variables). If you wanted to write to global variables, you'd need to prefix it with ::
.
The second example uses the 'initialization syntax', where you call the constructor of the named attribute with the passed item. Prefer this syntax if applicable, because it avoids default construction.
CodePudding user response:
Just change the name of the constructor function variables.
code:
#include <iostream>
using namespace std;
class Monolith{
public:
int height;
int weight;
string material;
string place;
Monolith (int height_1, int weight_1, string material_1, string place_1){
height = height_1;
weight = weight_1;
material = material_1;
place = place_1;
}
};
int main()
{
Monolith EiffelTower(300, 10000, "Iron", "Paris");
cout << EiffelTower.place;
return 0;
}