Search code examples
c++c++11syntaxconstructorderived-class

C++11: How to access base class member in a derived class?


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'

Solution

  • 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.