hello everyone,


My doubt is related to access specifier.

There is one code snippet -

class Base
{
    public:
     explicit Base();
     static int object_count;
    protected: 
     int id;
};
class child: public Base
{
     public:
     child(int val) : id(object_count++){}
};

This code is giving compilation error that id is not the member of child class
id is protected so child class can access it as its own member but why it is giving error.
Can anyone please answer to my query?

The problem is that pre-initialization occurs before the constructor is called.

Because of that, the data in the Base class is not initialized before the pre-initialization done in the Derived object.

The order of events that are occurring in your code are--

pre-initialization to derived object
derived object calls base constructor-
base pre-initialization is done-
base constructor finishes-
derived object finishes

-- it seems like a fairly loopdy-loo set of events, doesn't it?

Here's the modified code that accomplishes the same thing as yours above, without the problem of calling a variable that doesnt exist during pre-initialization--

#include <cstdlib>
#include <iostream>

using namespace std;

class Base
{
   public:
     explicit Base(){};
     static int object_count;
     protected:
        int id;
};
class child: public Base
{
    public:
       child(int val) {id = object_count++;}
};

int main(int argc, char *argv[])
{
    cin.get();
    return 0;
}

How about managing the id in the Base class, i.e.

class Base
{
    public:
        explicit Base() : id(object_count++) {}
        static int object_count;
    protected:
        int id;
};

int Base::object_count = 0;

class child: public Base
{
    public:
        child(int val){}
};
int main()
{
    child c(1);
    return 0;
}

mitrmkar,
what you said that is correct. but I wanted to access id from Child class.
I think Alex gave the right solution. pre-initialization occurs before the constructor is called.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.