-1

I've written the following code:

//--a.cpp--//
#include <stdio.h>

class A
{
public:
    void bar();
    virtual void foo()=0;
};

class B: public A
{
public:
    void foo()
    {
        A::bar();
    }
}
int main()
{
    B *b= new B();
    b->foo();
    return 0;
}

//--b.cpp--//
#include <stdio.h>
class A
{
public:
    void bar()
    {
        printf("class A");
    }
}

Now I'm comipilng and linking this modules as follow:

g++ -c a.cpp
g++ -c b.cpp
g++ -o bin a.o b.o

But the undefined reference error is raised by linker. I don't understand, why?

1 Answers1

3

You have not defined A::bar() in a.cpp. In B::foo() that method is called, but it does not have an implementation. So linker cannot link it.

In b.cpp you created another class name A, but it is unrelated to the first one. It will not create any problem here, but you will get Redefinition Error if you include any one file into another or both files in a third file (although including .cpp is uncommon). There must be only one definition of a name in one Translation Unit.

Common practice is to declare class in header file (.hXX) and implement the methods in source file (.cXX). If you want methods to be inlined then you may define in header or explicitly declare the method as inline. See Translation Unit , ODR.

Community
  • 1
  • 1
Rakib
  • 7,435
  • 7
  • 29
  • 45
  • This is undefined behaviour due to ODR violation - you aren't allowed to have two different class definitions with the same name. (This is why it's recommended to use anonymous `namespace` for class definitions that are meant to be local to a unit) – M.M May 06 '14 at 10:30