CyberShot
CyberShot

Reputation: 2335

Scope issue with vector inside class

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

class Dict
{
public:
    string line;
    int wordcount;
    string word;
    vector<string> words;
    Dict(string f)
    {
        ifstream myFile;
        myFile.open(f.c_str());
        if (myFile.is_open())
        {
            while(!myFile.eof())
            {
                myFile >> word;
                words.push_back(word);
            }
            cout << endl << "Wordcount: " << wordcount << endl;
        }
        else
            cout << "ERROR couldn't open file" << endl;
        myFile.close();
    }
};

int main()
{
    Dict d("test.txt");
    cout << words.size() << endl;
    return 0;
}

I get an error that words vector was not declared in main().

How can I make this visible to the compiler, since I already defined it in the class. Once an object is instantiated and the constructor is invoked, shouldn't words vector be created? But the compiler doesn't notice this.

How would I fix this?

Upvotes: 0

Views: 109

Answers (3)

Shahbaz
Shahbaz

Reputation: 47533

You should use d.words because words is a member of d.

In classes, each member, either variable or function belongs to an object. If you have two objects:

Dict d1("text1.txt");
Dict d2("text1.txt");

Then there is no way for the compiler to understand by words if you mean words in d1 or d2 unless you tell it. The way you tell it is to put the object name, followed by . followed by member name.

That is d1.words and d2.words are two different vectors.

Upvotes: 0

celtschk
celtschk

Reputation: 19721

Since you could have several objects of that class, each with its own instance of words, how is the compiler supposed to know which one you mean?

Just tell the compiler where to find the words:

cout << d.words.size();

Upvotes: 1

Kleist
Kleist

Reputation: 7985

words is a member in your Dict object d:

int main() {
    Dict d("test.txt");
    cout << d.words.size();
    return 0;
}

Upvotes: 4

Related Questions