Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

c++ - Initialize base class with no default constructor in constructor of derived class

I'm trying to create a subclass secondary which could be used with a parameter as well as it's overriding class primary. Now I get

no matching function to call

error. Could someone help me?

My code:
primary.h:

#ifndef PRIMARY_H
#define PRIMARY_H


class primary
{
    public:
        primary(int x);
        virtual ~primary();
    protected:
    private:
        int primary_x;
};

#endif // PRIMARY_H

primary.cpp:

#include "primary.h"

primary::primary(int x)
{
    primary_x = x;
}

primary::~primary()
{
    //dtor
}

secondary.h:

#ifndef SECONDARY_H
#define SECONDARY_H
#include "primary.h"


class secondary : public primary
{
    public:
        secondary();
        virtual ~secondary();
    protected:
    private:
};

#endif // SECONDARY_H

secondary.cpp:

#include "secondary.h"

secondary::secondary()
{
    //ctor
}

secondary::~secondary()
{
    //dtor
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because you don't have a default constructor the compiler complains that it can't create an object for primary, you should either add a parameter to the secondary constructor / give it a default value:

class secondary : public primary
{
    public:
        secondary(int x);
        virtual ~secondary();
    protected:
    private:
};

And then call the base class constructor:

secondary::secondary(int x) : primary(x)
{
    //ctor
}

Or:

secondary::secondary() : primary(5)
{
    //ctor
}

Or just add a default constructor for primary:

class primary
{
    public:
        primary(int x);
        primary() : primary_x(0) {}
        virtual ~primary();
    protected:
    private:
        int primary_x;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...