0

In a C++11 program I'd like to access the member b2 of a base class Base in a derived class Derived like so:

struct Base
{
    const int b1 = 0;
    const int b2 = 0;
    Base (int b1) : b1(b1) {} // ok
};

struct Derived : public Base
{
    Derived (int b1, int b2) : Base(b1), b2(b2) {} // error
    Derived (int b2) : Base(1), Base::b2(b2) {} // error
    Derived () : Base(1), this->b2(2) {} //error
};

Thread accessing base class public member from derived class claims that you can just access base class's members without any further ado. Same here: Accessing a base class member in derived class.

So could someone show me the correct syntax please?

g++ keeps throwing errors at me:

main.cpp: In constructor 'Derived::Derived(int, int)':
main.cpp:10:42: error: class 'Derived' does not have any field named 'b2'
main.cpp: In constructor 'Derived::Derived(int)':
main.cpp:11:41: error: expected class-name before '(' token
main.cpp:11:41: error: expected '{' before '(' token
main.cpp: At global scope:
main.cpp:11:5: warning: unused parameter 'b2' [-Wunused-parameter]
main.cpp: In constructor 'Derived::Derived()':
main.cpp:12:27: error: expected identifier before 'this'
main.cpp:12:27: error: expected '{' before 'this'
emacs drives me nuts
  • 2,785
  • 13
  • 23
  • 3
    Only the constructor of the class itself can initialize a `const` variable. So you'll have to do it there. – Sami Kuhmonen May 11 '20 at 12:55
  • Unrelated: you should prefer to initialize `b1` either inline (`= 0;`) or in the member initializer list (`: b1(...)`) but not both. – alter_igel May 11 '20 at 15:06
  • @alter Igel Does that cause any problems like undefined behavior? – emacs drives me nuts May 12 '20 at 05:33
  • Not undefined behaviour, the member initializer list simply overrides what appears in the default initializer (via [cppreference](https://en.cppreference.com/w/cpp/language/data_members#Member_initialization)). It's simply for clarity and maintainability reasons. Somebody else reading your code might be thrown off by the `= 0;` in `const int b1 = 0;` which actually has no effect, since this member is always initialized in the member initializer list. – alter_igel May 12 '20 at 17:24

1 Answers1

3

How to access base class member in a derived class?

You can access the base class members either through this pointer or implicitly by using the name unless it is hidden.

like so:

Derived (int b1, int b2) : Base(b1), b2(b2) {} // error

While the derived class can access the members of the base, it cannot initialise them. It can only initialise the base as a whole, and if the base has a constructor, then that constructor is responsible for those members.

So could someone show me the correct syntax please?

There is no syntax to do such initialisation. You must initialise the member in the base's constructor.

eerorika
  • 232,697
  • 12
  • 197
  • 326