| re: Inherit member variables?
Joseph Turian wrote:[color=blue]
> I'm having a little difficultly with inheritance.
> I want to have a class "SubT" inherit from class "T".
> SubT contains all the information in T, plus a little more based upon
> the member variables of T.
>
> For efficiency, I cannot merely have a T object in SubT.
> What I'd like is something as follows:
> class T {
> T(int a) : _a(a) {}
> protected:
> int _a;
> };
>
> class SubT : public T {
> SubT(int a) : _a(a), _b(a+a) {}
> SubT(T foo) : _a(foo._a), _b(foo._a+foo._a) {}
> public:
> int _b;
> };
>
> Unfortunately, SubT doesn't seem to contain member variable _a. Why
> not?[/color]
It does, but not directly, it contains T, which contains a.
[color=blue]
> Could someone suggest an efficient way to write the constructors for
> SubT?[/color]
You should use the T cosntructor, like this
SubT(int a) : T(a), _b(a+a) {}
SubT(T foo) : T(foo._a), _b(foo._a+foo._a) {}
[color=blue]
> [Assume that SubT needs to contain both _a, and _b, and that you can't
> optimize one out.]
>
> Joseph
>[/color]
john |