Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created a virtual class Base with 2 sub class Sub1 and Sub2. And for class Sub1, I made a constructor:
C++
Sub1(istream &source) {
        getline(source, s);
    }

Then i created a function to read Sub1 object from a text file:
C++
void Function(vector<Base*> v) {
    ifstream file;
    int i = 0;
    file.open("example.txt");
    static vector<Sub1> sub;
    while ( !file.eof() ) {
    sub.push_back(Sub1(file));
    v[i] = &sub[i];
    i++;
    }

But it didn't work. No problem found by editor or compiler, but i guest it a runtime error because the terminal screen remain unchanged for a while, then it said command executed now and failed (exit code 1). Thank in advance

What I have tried:

I think maybe i missed something about the ifstream.
Posted
Updated 5-Feb-23 8:14am

Without seeing the rest of your code, we have no idea if the fragment you show is even executed, let alone if it works. And we can;t run your code under the same conditions you do as we have no access to your data either.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
 
Share this answer
 
My best guess is that your s is some weired global variable and so is fooling around.
C++
Sub1(istream &source) {
        getline(source, s); // that s is very weired
    }

Second is that executing code in a constructor is always a bad idea. You better create that Sub1 object with the already completed string.
 
Share this answer
 
You are passing v by value. MOreover, you are accessing its (copy) items (v[i] without know if they actually exists.

Your code should be more similar to
C++
vector< Base * > Function()
  ifstream file("example.txt");
  vector < Base * > v{};
  while ( file )
  {
    v.push_back( new Sub1(file) );
  }
  return v;

Note that even such code is dangerous: you have to explicitely delete the heap allocated objects.
Consider using smart pointers instead.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900