Using parent class constructor initialiser-list in C++

泄露秘密 提交于 2019-12-24 18:30:09

问题


ORIGINAL POST

When compiled, the following code produces error C2436: '__ctor' : member function or nested class in constructor initializer list

in Child.h

#include Parent.h
class  Child : public Parent  
{
    public:
        Child (List* pList) 
            : Parent::Parent(pList)
        {
        }
};

Here the parent class:

in Parent.h

class __declspec(dllimport) Parent : public GrandParent  
{
    public:
       Parent (List* pList = NULL);
}

in Parent.cpp

Parent::Parent (List* pList)
: 
    m_a(1)
   ,m_b(1)
   ,GrandParent(pList)
{
}

Isn't it right the way to make the Child class calling the Parent class constructor?

PS Same happens if I split declaration and implementation of Child constructor into .h and .cpp. I cannot change the parent class code, as it is part of a pre-compiled library.

AFTER YOUR SUGGESTIONS, @Mape, @Mat, @Barry, @Praetorian

I realised the problem is due to the presence of another constructor in the Parent class. Thanks to your suggestions I generated the code reproducing the error (minimal, complete and verifiable) in a new post Managing in Child class multiple constructors (with initializer-lists) of parent class


回答1:


Adapted from your example, this compiles fine. Parent::Parent should be just Parent.

#define NULL 0

struct List;

class GrandParent
{
    public:
       GrandParent(List* pList = NULL) {}
};


class Parent : public GrandParent
{
    public:
       Parent(List* pList = NULL);
       int m_a;
       int m_b;
};

Parent::Parent(List* pList)
:
    m_a(1)
   ,m_b(1)
   ,GrandParent(pList)
{
}

class  Child : public Parent
{
    public:
        Child (List* pList)
            : Parent(pList)
        {
        }
};

int main(void)
{
    GrandParent grandparent(NULL);
    Parent parent(NULL);
    Child child(NULL);

    return 0;
}


来源:https://stackoverflow.com/questions/48691265/using-parent-class-constructor-initialiser-list-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!