Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ inheritance problem "undefined reference to"

While practicing inheritance in c++, I kept on getting the following error:

base1.o: In function Base1::Base1()': base1.cpp:(.text+0x75): undefined reference toBase2::Base2()' base1.o: In function Base1::Base1()': base1.cpp:(.text+0xa5): undefined reference toBase2::Base2()' collect2: ld returned 1 exit status make: * [test] Error 1

I removed all unnecessary code, so that only this is left:

base1.h :

#include "base2.h"
#ifndef BASE1_H_
#define BASE1_H_

class Base1 : public Base2 {  

public:
Base1();   
};

#endif

base1.cpp :

#include <QStringList>
#include <QTextStream>
#include "base1.h"
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);

Base1::Base1() : Base2() {
cout << "\nB1\n\n" << flush;
}

base2.h :

#ifndef BASE2_H_
#define BASE2_H_

class Base2 {

public:
Base2();
};

#endif

base2.cpp :

#include <QStringList>
#include <QTextStream>
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);


Base1::Base1() {
cout << "\nB2\n\n" << flush;   
}

child.cpp :

#include <QStringList>
#include <QTextStream>
#include "base1.h"
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);


Base1::Base1() {
cout << "\nB2\n\n" << flush;
}

This is probably an easy problem, but I have been spending like 2 hours looking for a solution on google and didn't find anything, so I would appreciate any help.


Hi,

thanks everyone for your answers so far.

I have changed base2.cpp to:

#include <QStringList>
#include <QTextStream>
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);


Base2::Base2() {
cout << "\nB2\n\n" << flush;
}

however, I still get the same error. I think it must have something to do with the "#include", but I don't know how to do it right :(.

like image 559
Anselm Avatar asked Apr 12 '26 09:04

Anselm


2 Answers

Probably a typo but in base2.cpp it should say Base2::Base2() instead of Base1::Base1()

like image 161
RvdK Avatar answered Apr 13 '26 22:04

RvdK


You have defined Base1::Base1() in three .cpp files and have not defined Base2::Base2() at all.

You need to define each member function exactly once.

like image 35
James McNellis Avatar answered Apr 13 '26 23:04

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!