Inheriting Constant Members

Hi everyone. I just ran into two problems with the following code. The first one is that the constant variable has to be initialized. The second one is in the constructor.

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
#include <iostream>

class A
{
  protected:
	const int n;
  public:
	A() {}                  /* Error: "A::A()" provides no initializer for:
        must be initialized in constructor base/member initializer list */
	~A() {}
	int get() { return n; }
};

class B : public A
{
  public:
	B(const int x) : n(x) {} /* Error: "n" is not a nonstatic data member or
        base class of class "B" illegal member initialization: 'n' is not a base
        or member*/
	~B() {}
};

int main()
{
	B foo(3);
	std::cout << foo.get() << std::endl;
	return 0;
}


I know the second one can be solved by redeclaring it in class B but I'm wondering if there is an alternative. Any help appreciated.
Initialize n in A's constructor.
Topic archived. No new replies allowed.