Home > OS >  I am getting LNK2005, LNK2001 and LNK1120 while using virtual function in my Program
I am getting LNK2005, LNK2001 and LNK1120 while using virtual function in my Program

Time:02-28

I am a beginner so this problem might seem trivial to you. So I have the following files:

  • base.h
  • derived.h
  • base.cpp
  • derived.cpp
  • TestCpp.cpp

base.h

#include <iostream>

namespace App
{
    class Base
    {
    public:
        virtual void Print();
    };
}

base.cpp

#include "base.h"

namespace App
{
}

derived.h

#include "base.h"

class Derived : public App::Base
{
public:
    void Print();
};

derived.cpp

#include "derived.h"

void Derived::Print()
{
    std::cout << "This works!! form Derived class\n";
}

and at last TestCpp.cpp

#include "derived.h"

int main()
{
    std::cout << "Hello World!\n";
    Derived d;
    d.Print();
    return 0;
}

I am getting the following Linker error: enter image description here

I don't know what it is I am doing wrong. Please help me out.

CodePudding user response:

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

CodePudding user response:

Just add a definition for Print() in the base.cpp file:

namespace App
{
    void Base::Print() { }
}

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