0

I didn't know what to give as a title, I expect more experienced stackoverflow.com users to improve it.

Let's say we have the class A

class A {
  void hello(){  cout << "i'm an A" << endl; }
}

and its sub-class B

class B: public A {
  void hello(){  cout << "i'm a B" << endl; }
}

Then we did somewhere in our program

A* array[2];
array[0] = new A;
array[1] = new B;
array[0]->hello(); // output: "i'm an A"
array[1]->hello(); // output: "i'm a B"

why doesn't the array[1].hello(); output I'm a B since we instanciated a B object for that base-class pointer ? and how to make it happen ?

3 Answers3

2

You have to make hello a virtual function:

class A {
    virtual void hello() { cout << "i'm an A" << endl; }
};

class B : public A {
    virtual void hello() override { cout << "i'm a B" << endl; } // 1) 
};

This tells the compiler that the actual function should not be determined by the static type (the type of the pointer or reference) but by the dynamic (run-time) type of the object.

1) The overridekeyword tells the compiler to check, if the function actually overrides a hello function in the base class (helps e.g. to catch spelling mistakes or differences in the parameter types).

MikeMB
  • 20,029
  • 9
  • 57
  • 102
  • I see, I was mistaken, I always thought that `virtual` is C++'s keyword for `abstract` methods. Now I got the right picture of it –  Nov 09 '15 at 23:13
  • @reaffer: You were partially correct: Abstract methods only make sense,if they are virtual. So you will always find the abstract keyword in front of the declaration of an abstract method. To tell the compiler that a method is not only virtual, but also abstract in c++, is to add `=0` after its declaration. – MikeMB Nov 09 '15 at 23:19
2

Couple of changes here:

make function hello in class A, a virtual and public: because by default it is private

class A {
public: 
virtual void hello(){ cout << "i'm an A" << endl; }
};

Similarly make hello in class B virtual

class B: public A {
virtual void hello(){  cout << "i'm a B" << endl; }
};
vishal
  • 2,258
  • 1
  • 18
  • 27
0

Since you have inherited class A in class B, derived class B will call the function from the Base class. You need to override the function in class B, as you want to change the Base class functionality.

You can do this with the override and virtual keywords.

http://en.cppreference.com/w/cpp/language/override

BoyUnderTheMoon
  • 741
  • 1
  • 11
  • 27