Inheritance, const& member

Is it possible to make a class which is a child of a class with a const& member? In other words, how to make the code (see below) working?

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
#include <vector>
#include <queue>

class A
{
  std::vector<float> vA;
  virtual void process();
public:
  A() { vA.push_back(0); }
};

class B : public A
{
  std::queue<int> qB; 
  virtual void process();
public:
  B() {qB.push(0);}
};


class ContainerA
{
  A const& mA; 
public:
  ContainerA(A const& a) : mA(a) {}
};

class ContainerB : public ContainerA
{
  B const& mB; 
public: 
  ContainerB(B const& b) : mB(b) {}
};

int main()
{
  B b; 
  ContainerB cb(b);
}
This is how it s declared: const A& mA; and the same for mB . You might need to initialize them.

Aceix.
Derived classes can't directly initialize base class members, they need to do it using the base class constructor.
1
2
3
4
5
6
class ContainerB : public ContainerA
{
  B const& mB; 
public: 
  ContainerB(B const& b) : ContainerA(b), mB(b) {}
};
Then you realize that the `mA' member in `ContainerB' is useless
So you may want to rethink your design.
Maeriden, but there is no constructor Container A(B const&). Unless I implement it...

ne555, you're right. I forgot to mention that both A and ContainerA are legacy code and supposed to remain unchanged or to be changed minimally.
Last edited on
Uh... it's a reference so I assumed it worked like a pointer. If I was wrong, I'm sorry.
> but there is no constructor Container A(B const&)
The one that's called is Container A(A const&)

> both A and ContainerA are legacy code and supposed to remain unchanged
I am not complaining about ContainerA, but ContainerB
Inheritance is a bad choice as you want to strength a precondition (instead of A objects you ask for B objects)
http://www.parashift.com/c++-faq/parkinglot-of-car-vs-vehicle.html


Also, I hope that you've got virtual ~A()
Topic archived. No new replies allowed.