How to initialize a const base-class member?

When my base class has a const member, how can I initialize it from a derived class? As const members can only be initialized in the initialization list, I put the initialization in the derived class' initialization list.

[code]
class Base
{
public:
Base() {}
Base(const int& value) : mValue(value) {}
virtual ~Base() {}
const int mValue;
};

class Derived : public Base
{
public:
Derived(const int& value) : mValue(value) {}
~Derived() {}
};
[/code]

This, however, yields the error:

[cod
[C++ Error] Unit1.cpp(15): E2312 'Base::mValue' is not an unambiguous base class of 'Derived'
[/code]

So, why does it think it is ambiguous and how to solve it? Thanks in advance,
bilderbikkel

Comments

  • : When my base class has a const member, how can I initialize it from a derived class? As const members can only be initialized in the initialization list, I put the initialization in the derived class' initialization list.
    :
    : [code]
    : class Base
    : {
    : public:
    : Base() {}
    : Base(const int& value) : mValue(value) {}
    : virtual ~Base() {}
    : const int mValue;
    : };
    :
    : class Derived : public Base
    : {
    : public:
    : Derived(const int& value) : mValue(value) {}
    : ~Derived() {}
    : };
    : [/code]
    :
    : This, however, yields the error:
    :
    : [cod
    : [C++ Error] Unit1.cpp(15): E2312 'Base::mValue' is not an unambiguous base class of 'Derived'
    : [/code]
    :
    : So, why does it think it is ambiguous and how to solve it? Thanks in advance,
    : bilderbikkel
    :

    [blue]You must call the Base class's constructor that initializes the const member in the Derived class's initializer list:[/blue]

    [code]
    class Base
    {
    public:
    Base() {}
    Base(const int& value) : mValue(value) {}
    virtual ~Base() {}
    const int mValue;
    };

    class Derived : public Base
    {
    public:
    Derived(const int& value) : [blue]Base(value)[/blue] {}
    ~Derived() {}
    };
    [/code]

  • Blimey! Thanks!
    bilderbikkel

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories