I have a huge C++ code base I'm working with.
I want to introduce a new subclass, and use it in a variety of different contexts, however my Java trained mind is having trouble with this in C++.
I wish to minimize code changes. So, my main class of interest (BAR
below) has a member variable of class FOO
. I wish to make a subclass of FOO
called FOOSUBCLASS
. In java this is trivial. Objects are stored by reference by default. This code does not do that (as seen below) can I massage this code, without changing interfaces (and without introducing references) and still make my application work?
class FOO {
};
class FOOSUBCLASS : FOO {
public:
FOOSUBCLASS(const int id) {_id = id;}
private:
int _id;
};
class BAR {
public:
BAR(const FOO foo) { _foo = foo;}
private:
FOO _foo;
};
Below, is my main:
FOOSUBCLASS fsc(1);
BAR b(fsc);
But this doesn't compile in VS2005. It says:
'type cast' : conversion from 'FOOSUBCLASS *' to 'const FOO &' exists, but is inaccessible
Get same compiler error if I add the obvious other constructor to BAR
BAR(const FOOSUBCLASS foo) { _foo = foo;}
My understanding of C++ is that it will copy the data from FOOSUBCLASS
into an object of class FOO
. (using the assignment operator, or a class overridden version of it) But in my case, I have additional member variables in FOOSUBCLASS
(and some overridden member functions) so I just don't want it to do that. I want my member variable _foo
to truly be of type FOOSUBCLASS
in some contexts, and FOO
in others. Is this even possible?
Thanks for your thoughts.