Otringal
Otringal

Reputation: 131

Initializer list doesn't detect publicly inherited member

Quick question: I thought that member initializing lists acted the same as normal initialization using '=' (except for const members which can only be defined using initializing lists), calling the constructors of the to-be-initialized objects with specific arguments that I'm passing, as in my below example (where I'm calling x's constructor with a value of 1). But to my surprize, in the case of a simple inheritance, the compiler complains for not seeing the member I'm trying to initialize with my constructor, although seeing the other one that gets initialized with usual '=' syntax:

#include <iostream> 
using namespace std;

class A
{
public:

    int x;
    int y;
};

class B : public A
{
public:

    B() : x(1)
    {
        y = 2;
    }
};

int main()
{   
    return 0;
}

If you run the above code, you'll see that while y gets detected with no problems, your compiler will say there is no such member named 'x' at the 'B() : x(1)' line. Why is that? The inheritance is public, y gets seen, no problems there, why not x as well?

Upvotes: 1

Views: 157

Answers (2)

gsamaras
gsamaras

Reputation: 73376

You can't initialize x from the initializer list of class B, because only class A can initialize its members.

By the way, making the data members public is not a good idea. Here is an example of how your code would work:

#include <iostream> 
using namespace std;

class A
{
public:
    A(int x, int y) : x(x), y(y) {}
protected:

    int x;
    int y;
};

class B : public A
{
public:

    B() : A(1, 5000)
    {
        y = 2;
    }
};

int main()
{   
    return 0;
}

Upvotes: 1

Otringal
Otringal

Reputation: 131

I think I've found the answer:

My objects are already being initialized once when the constructor of class A is being executed, thus I cannot re-initialize it when running B's constructor. Reassigning y to a value of 2 is ok, but re-initializing x with 1 being passed as its constructor argument is the cause of the compiler's error. Am I missing anything else???

Upvotes: 0

Related Questions