s.eyal
s.eyal

Reputation: 35

C++ how to extend class from different file without headers

I’m trying to do a basic polymorphism program and am having some problems. I have 2 files, Currency.cpp and Dollar.cpp

Currency.cpp looks something like this

#include <iostream>
using namespace std;
class Currency{
/* code */
};

Dollar.cpp looks something like this

#include <iostream>
using namespace std;
class Dollar : protected Currency{
/* code /*
};

When I try to build paths between the files (command shift b on mac) it tells me that Currency is not recognized as a class (in Dollar.cpp that is). I’m not supposed to use header files as this is for an assignment that specifies so. What am I supposed to do?

I use vs code on a 2020 m1 Mac if that has anything to do with it

Edit: Thanks for all the feedback. From what I can tell what I'm asking here isn't possible. This assignment is for a data structures and algorithms class that accepts multiple languages, so maybe the teacher is rusty in c++ or something. I'm just gonna use header files and the professor will just have to deal with it lol.

Upvotes: 0

Views: 811

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596582

I’m not supposed to use header files as this is for an assignment that specifies so.

The code will not work as shown. Dollar.cpp needs to know what the Currency class looks like in order to use it.

The ideal solution is to use a header file to share declarations across translation units, use the .cpp files to implement definitions, eg:

Currency.h:

#ifndef CurrencyH
#define CurrencyH

class Currency{
    /* code */
};

#endif

Currency.cpp:

#include <iostream>
#include "Currency.h"
using namespace std;

// implement Currency's methods as needed...

Dollar.cpp:

#include <iostream>
#include "Currency.h"
using namespace std;

class Dollar : protected Currency{
    /* code /*
};

But, since that is not an option for you, you have no choice but to copy the entire Currency class declaration into Dollar.cpp directly, and make sure it exactly matches the class declaration in Currency.cpp to avoid any ODR violations, eg:

Currency.cpp:

#include <iostream>
using namespace std;

class Currency{
    /* code */
};

// implement Currency's methods as needed...

Dollar.cpp:

#include <iostream>
using namespace std;

class Currency{
    /* code */
};

class Dollar : protected Currency{
    /* code /*
};

Upvotes: 5

Related Questions