简体   繁体   中英

C++ inherited function in cpp file

Topic is a base class with a method called possibleEvaluationQuestions() declared in Topic . AlgebraTopic is a subclass of Topic . In AlgebraTopic 's cpp file I've declared the function:

vector<EvaluationQuestion *> AlgebraTopic::possibleEvaluationQuestions()
{
    return vector<EvaluationQuestion *>();
}

But get the warning "out-of-line definition..” in Xcode. It says 'possibleEvaluationQuestions()' isn't declared in AlgebraTopic , which it isn't, but, it is declared in the superclass Topic . What am I doing wrong?

When you define :

vector<EvaluationQuestion *> AlgebraTopic::possibleEvaluationQuestions()

The compiler is looking for the corresponding declaration : in C++ you can't define a member function without having it declared.

The declaration of the base class function is the declaration of another, different function : both exist for any AlgebraTopic object.

You can convince yourself with this :

struct X
{
    virtual void foo() { std::cout << "base\n"; }   
};

struct Y : X
{
    void foo() { std::cout << "derived\n"; }
};

int main(){

    Y y;
    y.foo();
    y.X::foo();
}

Output:

derived

base

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM