1

I meet a problem when constructing a class. class "Graph" import a class "Bag" in another file and use "Bag" as its component.

//Graph.h
#ifndef GRAPH_H
#define GRAPH_H
#include <fstream>
#include <iostream>
#include <vector>
#include "Bag.h"
class Bag;
class Graph
{
public:
    Graph(int V);
    Graph(std::ifstream& in_file);
    int getV() { return V; }
    int getE() { return E; }
    void addEdge(int v, int w);
    void showadj() ;
private:
    int V;
    int E;
    std::vector<Bag> adj;
};
#endif

And "Bag.h" is as follow:

//Bag.h
#ifndef BAG_H
#define BAG_H
#include <vector>
#include <iostream>
class Bag
{
public: 
    Bag();
    void addBag(int i) { content.push_back(i); }
    void showBag();
private:
    std::vector<int> content;
};

#endif 

Graph.cpp:

//Graph.cpp
#include "Graph.h"
#include "Bag.h"
Graph::Graph(int V) : V(V), E(0)
{
    for (int i = 0; i < V; i++)
    {
        Bag bag;
        adj.push_back(bag);
    }
}

Bag.cpp(sorry, forget it):

#include "Bag.h"
void Bag::showBag()
{
    for (int i : content)
    {
        std::cout << i << " ";
    }
}

When I try to complie these two classes, an error comes out saying:

C:\Users\ADMINI~1\AppData\Local\Temp\ccMj4Ybn.o:newtest.cpp:(.text+0x1a2): undef
ined reference to `Bag::Bag()'
collect2.exe: error: ld returned 1 exit status
Aperion
  • 273
  • 3
  • 7

1 Answers1

4

You need to also implement your constructor Bag::Bag() as it is missing in your Bag.cpp file.

This is what the error tells you. If you don't need the constructor, then you should remove it from your class definition, which would also solve this error.

An alternative would be to provide an empty constructor in your Bag.h file

class Bag
{
public: 
    Bag() {}
...
}
Devolus
  • 21,661
  • 13
  • 66
  • 113