Inherit member variables?

Discussion in 'C++' started by Joseph Turian, Nov 26, 2005.

  1. 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
     
    Joseph Turian, Nov 26, 2005
    #1
    1. Advertising

  2. Joseph Turian wrote:
    > 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
     
    John Harrison, Nov 26, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. dwok
    Replies:
    7
    Views:
    710
    Hal Rosser
    Mar 4, 2005
  2. Replies:
    10
    Views:
    537
    Steven Bethard
    May 22, 2006
  3. Replies:
    17
    Views:
    508
    Bruno Desthuilliers
    Sep 22, 2006
  4. Replies:
    9
    Views:
    985
  5. K. Frank
    Replies:
    20
    Views:
    427
Loading...

Share This Page