5
class ZooAnimal {
public:
    virtual void draw();
    int resolveType() {return myType;}
protected:
    int myType;
};

class Bear : public ZooAnimal {
public:
    Bear (const char *name) : myName(name), myType(1){}
    void draw(){ };
private:
    std::string myName;
};

void main()
{
   
}

When I am compiling above code I am geeting following error

error C2614: 'Bear' : illegal member initialization: 'myType' is not a base or member

Why am I getting the above error, as we can access protected member from the derived class?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
venkysmarty
  • 11,099
  • 25
  • 101
  • 184
  • 3
    See this discussion http://stackoverflow.com/questions/2290733/initialize-parents-protected-members-with-initialization-list-c – user1202136 Apr 24 '12 at 08:58
  • Possible duplicate of [error C2614: 'ChildClass' : illegal member initialization: 'var1' is not a base or member](http://stackoverflow.com/questions/10138424/error-c2614-childclass-illegal-member-initialization-var1-is-not-a-base) – Akhil V Suku Jan 04 '16 at 10:08

1 Answers1

15

You can't initialize base class member in derived class initializer lists.

You'll need to provide a constructor to the base class:

class ZooAnimal {
public:

    ZooAnimal(int type) : myType(type) {}

    virtual void draw();
    int resolveType() {return myType;}
    protected:
    int myType;
};

and call it from the derived class:

class Bear : public ZooAnimal {
public:
                            //here//
Bear (const char *name) : ZooAnimal(1), myName(name) {}

void draw(){ };
private:
    std::string myName;
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625