0

I have a class A and a class B like this :

class A
{
public:
   A(){}
};

class B : public A
{
public:
   B() : A()
   {
      value = 10;
   }
   int Value()
   {
      return value;
   }

protected:
   int value;
}:

I have this code :

int main()
{
   A* a = new B();
   // how can I access to Value() ? I would like to make that :
   int val = a->Value();
   // must i cast a to B ? how ?
}

thanks for your help.

flow
  • 4,828
  • 6
  • 26
  • 41

4 Answers4

6

Make Value() a pure virtual function in A (also add a virtual destructor):

class A
{
public:
  A(){}
  virtual ~A(){}
  virtual int Value() = 0;
};
HerrJoebob
  • 2,264
  • 16
  • 25
  • 1
    HerrJoebob is right. It is always good practice to make the root class pure abstract (http://en.wikibooks.org/wiki/C%2B%2B_Programming/Classes/Abstract_Classes/Pure_Abstract_Classes). It allows you to program to an interface (http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface). – Carl Dec 17 '12 at 20:58
1

The thing is, Virtual() isn't inherited. It isn't defined in A.

declare Value() in A as a pure virtual.

virtual int Value() = 0;

You can't access Value() because as far as the compiler is concerned, there is no Value() function in A (which is the object type you are creating).

Aeluned
  • 769
  • 5
  • 11
1

Use virtual methods

class A
{
public:
   A(){}
   virtual int Value() = 0;
   virtual ~A(){}
};

class B : public A
{
public:
   B() : A()
   {
      value = 10;
   }
   int Value()
   {
      return value;
   }

protected:
   int value;
}:

Also keep in mind ( tell don't ask principle ).

AlexTheo
  • 4,004
  • 1
  • 21
  • 35
0

Do this instead:

B* b = new B();

If you need functionality of B make a B.

djechlin
  • 59,258
  • 35
  • 162
  • 290