0

I am currently trying to understand if I could use this pointer in an initialization list.I read this SO post which states

Yes. It's safe to use this pointer in initialization-list as long as it's not being used to access uninitialized members or virtual functions, directly or indirectly, as the object is not yet fully constructed. The object child can store the this pointer of Parent for later use!

So I decided to try this using the following code

struct base
{
    int bse;
    base() {
        std::cout << "Base constructor called \n";
    }
};
struct foo
{

    foo() {
        std::cout << "Foo constructor \n";
    }

    foo(int a) {
        std::cout << "Foo parameter \n";
    }
};

struct test : public base
{
    foo a;
    test(int _a) : this->bse(24) , a(_a) {
        std::cout << "test constructor";
    }
};

Now from the above example the base class constructor is fully constructed however the base class is still not fully constructed.In the initialization list I am attempting to call an inherited member variables that has been fully constructed.As the link that I already posted mentions that it is safe to use this pointerin an initialization list as long as the object being referenced is fully constructed.Please correct me if I misunderstood the quote. So my question is in my case why am I getting the error

main.cpp: In constructor 'test::test(int)':
main.cpp:27:20: error: class 'test' does not have any field named 'bse'
     test(int _a) : bse(24) , a(_a) {
Community
  • 1
  • 1
MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 1
    This is a duplicate question, because it doesn't matter whether you use `this` for accessing inherited fields or not. It doesn't affect the impossibility to do this. – Wolf May 19 '17 at 06:54
  • 1
    The question title is very misleading, since it's not the `this` part that matters. – Wolf May 19 '17 at 06:57

1 Answers1

3
test(int _a) : this->bse(24) , a(_a) { ... }

is not valid since only member variables and base classes can be initialized in the initializer list. Members of base classes cannot be initialized there.

You have to initialize and/or set the value of the bse member of the base class using other ways.

  1. Provide a constructor in the base class that takes an int. Then, you can use:

    test(int _a) : base(24) , a(_a) { ... }
    
  2. Set the value in the body of test().

    test(int _a) : a(_a) { bse = 24; ... }
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270