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

Categories

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

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

1 Answer

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;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...