I’m a complete c++ beginner.
I’m trying to do a couple things that seem pretty basic: Create an object of a certain class, store it in a vector, then output a value of that object. At the moment it outputs a rectangle character, no matter what character I store.
Here’s the code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <conio.h>
#include <time.h>
#include <windows.h>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class terrainType
{
public:
string name;
char symbol;
int freq;
terrainType(string,char,int);
};
terrainType::terrainType(string name, char symbol, int freq)
{
name=name;
symbol=symbol;
freq=freq;
}
int main()
{
vector<terrainType> terrainTypes;
terrainType dirt("dirt",'.',1);
terrainTypes.push_back(dirt);
cout << terrainTypes[0].symbol;
return 0;
}
Any advice or background info is appreciated. Thanks!
The three assignments you have in the constructor are effectively no-ops (you’re assigning each variable to itself):
The issue is that you have two things called
name, and you expect the compiler to figure out that inname=namethe left-hand side refers to one of them, whereas the right-hand side refers to the other.The cleanest way to fix this is by changing to constructor like so:
The rules of the language are such that this would have the intended meaning.
Another alternative is to avoid using the same identifier to refer to both a member and a function argument:
Yet another alternative is to prefix member access with
this->: