相关文章推荐
纯真的石榴  ·  [Solved] ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams You have clearly realized that you need to provide an actual definition for Derived::Print() , so what makes you think things are different for Base::Print() ? Adrian Mole Feb 28, 2022 at 11:39 You need to add a definition of virtual void Print(); in Base or make it pure virtual by writing virtual void Print() = 0; instead. user17732522 Feb 28, 2022 at 11:39 Does this answer your question? What is an undefined reference/unresolved external symbol error and how do I fix it? , specifically this answer . user17732522 Feb 28, 2022 at 11:41 @user17732522 that did work out. I thought if you use the keyword "virtual" you had to skip the definition in the base class. Anirudh Kanaparthy Feb 28, 2022 at 11:52 @AnirudhKanaparthy A pure virtual function doesn't need a definition, but simply a virtual function does, because you can still create a Base object directly and call .Print() on it. Which function definition should then be called? If you make it pure virtual, the class becomes an abstract class , for which only derived instances can be created, so the definition isn't required anymore. user17732522 Feb 28, 2022 at 11:55

The problem is that you've only declared the virtual function Print in class Base but not defined it.

And from C++03 Standard: 10.3 Virtual functions [class.virtual]

A virtual function declared in a class shall be defined, or declared pure (10.4) in that class, or both; but no diagnostic is required (3.2).

So the way to solve this problem would be to either implement/ define the virtual member function Print in class Base or make it pure virtual by replacing the declaration with virtual void Print() = 0; inside class Base

Solution 1

Base.cpp

#include "base.h"
namespace App
    void Base::Print()

Solution 1 DEMO

Solution 2

Base.h

#include <iostream>
namespace App
    class Base
    public:
        virtual void Print() = 0;

Solution 2 DEMO

It may not have anything inside it, but it should be there.

Or indicate Print() to be defined in the derived class by making it pure:

virtual void Print() = 0;

Any one of the 2 options work. Also in your derived class it's better to make Print() as override: (Click here to know why)

class Derived : public App::Base
public:
    void Print() override;
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.