inheritance + stl map

im trying to add "items" to a map that is declared in class A that are class B and C types

lets say we have these classes
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
class A
{
protected:
map<int, A*> database;
string something;
public:
A(){}
~A(){
//deletes all items in database
}
void showDatabase()
{
//some loop that iters through the map to print out whats in it
}
};

class B : public A
{
public:
B(newsomething){something = newsomething;}
void BAddData()
{
database[10] = new B(some);
}
};

class C : public A
{
C(newsomething){something = newsomething;}
void CAddData()
{
database[30] = new C(some);
}
};


main function

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
A a;
B b;
C c;

b.BAddData();
c.CAddData();
a.showDatabase();

return 0;
}


i have something similar to this but the problem i have is that nothing going into the map.
i have an idea why the database shows up as empty its because im calling showdatabase in separate instance from the other 2. im just curious how to add items to the map that is declared in the base class and the items remain there until the program ends
If all instances should use the same database object:

1
2
3
4
5
6
class A
{
    protected:
         static std::map<int, A*> database;
    // ...
};


And somewhere in an implementation file (say, A.cc)
std::map<int, A*> A::database ;

Consider using a smart_pointer instead of a raw pointer.
b and c have their own copies of base class A. a, b and c are distinct objects. try b.showDatabase() and c.showDatabase().
@ bandicoot360
i want to be able to see both b and c items
@JLBorges

where do i exactly put this line std::map<int, A*> A::database ;
and only in the A class ?
> where do i exactly put this line std::map<int, A*> A::database ;

Put it in one (and only one) .cpp (or .cc) file.
Topic archived. No new replies allowed.