Pergunta

I try to extend class, but use construct from first class, what am i doing wrong?

class Test
{
public:
    Test(const char *str)
    {
        cout<<str<<endl;
    }
    virtual const char *getName() =0;
};

class Babah : public Test
{
    const char *getName()
    {
        return "Babah extends Test";
    }
};
Foi útil?

Solução

The problem in your code is that your Test class does not have a 'default' (non parameterised) constructor. So you need to call it explicitly in child class.

Try the following code:

class Test
{
public:
    Test(const char *str)
    {
        cout<<str<<endl;
    }
    virtual const char *getName() =0;
};

class Babah : public Test
{
public:
    Babah(): Test("foo")    // Call the superclass constructor in the
                            // subclass' initialization list.
    {
          // do something with Babah or keep empty
    }
    const char *getName()
    {
        return "Babah extends Test";
    }
};
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top