Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error C2614: 'ChildClass' : illegal member initialization: 'var1' is not a base or member

I am getting the following error in C++:

error C2614: 'ChildClass' : illegal member initialization: 'var1' is not a base or member

Class Base 
{
    protected:
    int var1;
public:
    Base()
    {
        var1=0;
    }
}


class Child : public Base
{
    int chld;
    public: 
    Child() : var1(0)
    {
        chld=1;
    }
}

I feel what I have done is as per OO protocol. Here var1 is a data member of Base class with protected as the access specifier. So It can be inherited and it would become private in child.

Don't understand why am I getting the error?

like image 357
codeLover Avatar asked Apr 13 '12 09:04

codeLover


2 Answers

It doesn't work for the exact reason the error message provides you: you can only use initializer lists with direct members or base classes.

In your case, you don't even need to initialize var1, since Base::Base() will be called by Child's constructor, which will set var1 to 0.

If you want a different value, you'll have to overload Base constructor and call it explicitly:

class Base 
{
protected:
     int var1;
public:
     Base() : var1(0)
     {
     }
     Base(int x) : var1(x)
     {
     }
};

class Child:public Base
{
    int chld;
public: 
    Child(): Base(42) , chld(1)
    {
    }
};
like image 113
Luchian Grigore Avatar answered Oct 02 '22 10:10

Luchian Grigore


You can't initialize a member of a base class, only of the current class. Use a parameterized constructor in the base class.

Class Base 
{
  protected:
     int var1;
     Base( int var ) : var1(var)
     {}
  public:
     Base()
     {
        var1=0;
     }
};

class Child:public Base
{
      int chld;
   public: 
      Child():Base(0)
      {
         chld=1;
      }
};
like image 23
sharptooth Avatar answered Oct 02 '22 10:10

sharptooth