Inherit member variables?

J

Joseph Turian

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
 
J

John Harrison

Joseph said:
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?

It does, but not directly, it contains T, which contains a.

Could someone suggest an efficient way to write the constructors for
SubT?

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) {}
[Assume that SubT needs to contain both _a, and _b, and that you can't
optimize one out.]

Joseph

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top