1

I am trying to access derived class' private members via an object of the base class. Here is what I'm trying to do :

 class A {

      private:

           int a, b;

      public:
           A(_a, _b) : a(_a), b(_b) {}
           int getA() { return a; }
           int getB() { return b; }
 };

 class B : public A {

      private:
           int c;

      public:
           B(_a, _b, _c) : A(_a, _b), c(_c) {}
           int getC() { return c; }

 };

 vector<A*> objects;
 A* retVal = new B(1,2,3);
 objects.push_back(retVal);

Now how is it possible to access this?

 objects[0] -> getC();

I am a little confused.

Thanks in advance.

Daniel Heilper
  • 1,182
  • 2
  • 17
  • 34
user3279394
  • 141
  • 7

3 Answers3

2

If you know the object is actually of derived type B, you can do this:

static_cast<B*>(objects[0])->getC();

If you are wrong and the object is not actually of type B (or a subclass of B), your program will invoke undefined behavior, so don't do that.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

You can provide a pure virtual function in your base class

 class A {

      private:

           int a, b;

      public:
           A(_a, _b) : a(_a), b(_b) {}
           int getA() { return a; }
           int getB() { return b; }
           virtual int getC() = 0;
 };

 class B : public A {

      private:
           int c;

      public:
           B(_a, _b, _c) : A(_a, _b), c(_c) {}
           virtual int getC() { return c; }

 };
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • I have other derived classes too. I think this does not work. Is there another way? – user3279394 May 25 '14 at 08:31
  • @user3279394 _'Is there another way?'_ Not in a simple straightforward manner. May be inheritance isn't the right instrument to solve your real use case. Hard to give you advice without knowing it. – πάντα ῥεῖ May 25 '14 at 08:34
0

I don't see any clean way to do what you want. I think it is at odds with the way inheritance is meant to be used in c++: if your derived class adds new methods then it should really be regarded as a new type, i.e. something more than just a morphing of the base type. (What you are trying to do is more objective-C-like philosophy, where methods calls are resolved runtime.) My suggestion is to reconsider your design and keep B-object conceptually separated from A-objects.

Emerald Weapon
  • 2,392
  • 18
  • 29