References and inheritence

Hi everyone,

I want to define a class hierarchy where all classes inherited from the base class inherit a member which is a reference. Is this possible since references need to be initialized? Is declaring a reference within a class a normal thing to do?

Cheers,

Glenn
This is perfectly doable.

The inherited reference is typically constructed in the ctor of the parent class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Parent
{
public:
  Parent(int& target)
    : nRef( target )             // initialize the reference
  {
  }

protected:
  int& nRef;
};

class Child : public Parent
{
public:
  Child(int& target)
    : Parent(target)
  {
  }
};
Great - thank you.
Topic archived. No new replies allowed.