Connecting Tech Pros Worldwide Forums | Help | Site Map

Inherit member variables?

Joseph Turian
Guest
 
Posts: n/a
#1: Nov 26 '05
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?
Could someone suggest an efficient way to write the constructors for
SubT?
[Assume that SubT needs to contain both _a, and _b, and that you can't
optimize one out.]

Joseph


John Harrison
Guest
 
Posts: n/a
#2: Nov 26 '05

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
Closed Thread


Similar C / C++ bytes