Adriaan
Adriaan

Reputation: 715

Use derived class in base class while derived class is declared after the base class

I have the header file

#ifndef CATEGORY_H
#define CATEGORY_H

#include <functional>
#include <string>
#include <vector>

class Category
{
    private:
        std::string nameCategory;
        std::vector<Rule> setOfRules;
    protected:
    public:
        Category();
        Category(std::string nameCategory);
        void setIndexBankAccountEntry(unsigned int iBankAccountEntry);
};

class Rule : public Category
{
    private:
        std::function<void(int)> rule;
    protected:
    public:
        Rule();
        Rule(std::function<void(int)> rule);
};
#endif

in which the command std::vector<Rule> setOfRules; gives the error that Rule was not yet declared.

Switching the order of the declarations of the two classes gives

#ifndef CATEGORY_H
#define CATEGORY_H

#include <functional>
#include <string>
#include <vector>

class Rule : public Category
{
    private:
        std::function<void(int)> rule;
    protected:
    public:
        Rule();
        Rule(std::function<void(int)> rule);
};

class Category
{
    private:
        std::string nameCategory;
        std::vector<Rule> setOfRules;
    protected:
    public:
        Category();
        Category(std::string nameCategory);
        void setIndexBankAccountEntry(unsigned int iBankAccountEntry);
};
#endif

but then I get the error that expected class-name before ‘{’ token for the line class Rule : public Category.

How do I solve this?

Upvotes: 0

Views: 48

Answers (2)

Rishi
Rishi

Reputation: 1395

You can use a forward declaration for class Rule ( based on the first example ).

class Rule;
class Category
{
    private:
        std::string nameCategory;
        std::vector<Rule> setOfRules;
    protected:
    public:
        Category();
        Category(std::string nameCategory);
        void setIndexBankAccountEntry(unsigned int iBankAccountEntry);
};
// class Rule definition here 

Check here

Upvotes: 2

Serikov
Serikov

Reputation: 1209

You can forward declare class Rule:

#ifndef CATEGORY_H
#define CATEGORY_H

#include <functional>
#include <string>
#include <vector>

class Rule; // <-- here

class Category
{
    private:
        std::string nameCategory;
        std::vector<Rule> setOfRules;
    protected:
    public:
        Category();
        Category(std::string nameCategory);
        void setIndexBankAccountEntry(unsigned int iBankAccountEntry);
};

class Rule : public Category
{
    private:
        std::function<void(int)> rule;
    protected:
    public:
        Rule();
        Rule(std::function<void(int)> rule);
};
#endif

Upvotes: 0

Related Questions