Simple vector across files.

Hi,

Trying to get my head back into C++.
I am trying to split between a .cpp file and a .h file.
I am trying to employ constructors and destructors.
This might seem quite simple or a dumb question.
Can someone set me straight?

Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

#ifndef QUIVEC_H_INCLUDED
#define QUIVEC_H_INCLUDED
#include <iostream>
#include <vector>

class Quivec
{

private:
    vector<int> quivec;
    vector<int>::const_iterator i;

public:
    Quivec(vector quivec, vector<int>::const_iterator i);
};

Quivec::Quivec(vector<int> quivec, vector<int>::const_iterator i)
{
    quivec.push_back(1);
    quivec.push_back(2);
    quivec.push_back(4534);
    quivec.push_back(23);
    quivec.push_back(1123);
    quivec.push_back(1231);
    quivec.push_back(4351);

    for(i=quivec.begin(); i!=quivec.end(); i++)
    {
        cout << (*i) << " ";
    }
    cout << endl;
}

#endif // QUIVEC_H_INCLUDED

main.cpp:

#include <iostream>
#include "quivec.h"

using namespace std;

int main()
{
    Quivec *qv = new Quivec;
    return 0;
}



http://cpp.sh/2afr

Create 3 files as indicated.
In your project IDE / Makefile, add quivec.cpp and main.cpp as being source files.

Remove the comments from
//!!#include "quivec.h"
when you really have 3 files.
Last edited on
quivec.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef QUIVEC_H_INCLUDED
#define QUIVEC_H_INCLUDED

#include <iostream>
#include <vector>

class Quivec
{
private:
   std::vector<int> quivec;

public:
   Quivec();
};

#endif 

quivec.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "quivec.h"

Quivec::Quivec()
{
   quivec.push_back(1);
   quivec.push_back(2);
   quivec.push_back(4534);
   quivec.push_back(23);
   quivec.push_back(1123);
   quivec.push_back(1231);
   quivec.push_back(4351);

   for (const auto& itr : quivec)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}

main.cpp
1
2
3
4
5
6
#include "quivec.h"

int main()
{
   Quivec* qv = new Quivec;
}

1 2 4534 23 1123 1231 4351
That's great!
Thank you for your help!

So, apart from a few bells and whistles, was the main problem that I had function code in the .h file instead of its own .cpp file?

Thanks,.
So, apart from a few bells and whistles, was the main problem that I had function code in the .h file instead of its own .cpp file?

I wouldn't say that was your main problem.

Line 18-33 (in your OP): You're passing Quivec in by value., modifying it, then exiting thereby losing the contents of what you just built. Because the argument and you class member have the same name, the compiler chooses the argument over the class member.

Furry Guy corrected that for you by not passing any arguments to Quivec() {line 3}, thereby referring to the class member.

Topic archived. No new replies allowed.