Jack Satriano
Jack Satriano

Reputation: 2029

C++ Constructor inheritance not working correctly

This is the dependent class header

#ifndef TransHeader
#define TransHeader
#include <string>
#include "CipherHeader.h"

using namespace std;
class Trans : public Cipher {
    public:
    Trans(string filenameIn);
    const static int MAXSIZE = 10000;
    void createArray();
    void transEncrypt();
    void transDecrypt();


    private:
        //string Key;
        //string inputData;
        char dataArray[MAXSIZE][MAXSIZE];


};

#endif

This is the inherited header

#ifndef CipherHeader
#define CipherHeader
#include <string>
using namespace std;

class Cipher {
    public:
        const static int MAXSIZE = 10000;
        Cipher(string filenameIn);
        void getKey();
        void flagHandle(string);
        string Key;
        string inputData;
        string filename;
        string flags;

        string readFile();
        void writeFile();
    private:




};

#endif

The problem is after I call the base constructor

Trans::Trans(string filenameIn) : Cipher(filenameIn) {}

I cannot call the constructor in a normal file like so:

#include "Trans.cpp"

int main() {
string a  = "asdf";
Trans *c = new Trans(a);

}

This results in this error:

g++ test.cpp -o test.out
/tmp/ccbuqMYr.o: In function `Trans::Trans(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
test.cpp:(.text+0x35): undefined reference to `Cipher::Cipher(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/tmp/ccbuqMYr.o: In function `Trans::Trans(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
test.cpp:(.text+0xa5): undefined reference to `Cipher::Cipher(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status

replacing Trans with Cipher works just fine and runs. I have tried everything I know, googled excessively, and cannot figure out this error. Other design problems, ect will be dealt with later, this is my main problem. Please help.

EDIT:: definition of Cipher

Cipher::Cipher(string filenameIn) {

filename = filenameIn;

readFile();
getKey();

}

Upvotes: 0

Views: 532

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254431

You need all the source files in the build:

g++ test.cpp trans.cpp cipher.cpp -o test

This will give you a new error because you're including the trans.cpp source file from test.cpp, rather than the header file - fix that, and it should build with no further problems.

Upvotes: 1

Adrian Cornish
Adrian Cornish

Reputation: 23858

Ok rule 1 - never ever ever put a 'using' statement in a header file! ;-)

Ok you need to call the base class constructor.

So :

Trans::Trans(const std::string &f) // notice pass by reference
    :Cipher(f)
{
}

Upvotes: 3

Related Questions