I'm pretty new to C++.
I'm having an issue where my class constructor seemingly can't initialize a vector class member. The constructor would need to read a file, collect some data and then resize the vector during run time.
I created a simpler example to focus on the issue.
Here's the header file (test.h
):
// File Guards
#ifndef __TEST_H
#define __TEST_H
// Including necessary libraries
#include <vector>
// Use the standard namespace!
using namespace std;
// Define a class
class myClass
{
// Public members
public:
// vector of integers
vector<int> vec;
// Declare the constructor to expect a definition
myClass();
};
// Ends the File Guard
#endif
And here's the source file:
// Including the necessary headers
#include <iostream>
#include "test.h"
// Defining the constructor
myClass::myClass()
{
// Loop control variable
int i;
// For loop to iterate 5 times
for (i = 0; i < 5; i++)
{
// Populating the vector with 0s
vec.push_back(0);
}
}
// Main function to call the constructor
int main()
{
// Create a "myClass" object
myClass myObject;
// iterating through the vector class member
for (int x : myObject.vec)
{
// Outputting the elements
cout << x + " ";
}
// Return statement for main function
return 0;
}
I'd expect five 0's to be printed, but instead, nothing happens. I've thought about this for awhile and haven't found a resolution yet. Any ideas as to what's happening here?