2

Lets say I have a parent Class:

Class Parent{
public:
virtual void doSomething(){}
}

and two children:

Class Son: public Parent{
public:
  void doSomething(){
  // Do one thing
  }
}

Class Daughter: public Parent{
public:
  void doSomething(){
  // Do another thing
  }
}

If I setup an instance of a child class like this:

Parent obj = Son();

How do I properly invoke the doSomething() method that is defined by Son and not the empty function in Parent

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
slayton
  • 20,123
  • 10
  • 60
  • 89
  • See also: http://stackoverflow.com/questions/7313622/calling-method-of-child-class-on-a-vector-of-parent-class –  Mar 21 '12 at 17:16
  • See also: http://stackoverflow.com/questions/818259/c-how-to-call-a-parent-class-method-from-contained-class –  Mar 21 '12 at 17:16
  • See also: http://stackoverflow.com/questions/1847661/calling-a-child-class-method-when-processing-a-list-of-parent-class-objects –  Mar 21 '12 at 17:17
  • See also: http://stackoverflow.com/questions/6568778/c-call-overwritten-child-function-within-parent-function –  Mar 21 '12 at 17:18
  • See also: http://stackoverflow.com/questions/5754590/possible-for-a-parent-class-to-call-its-child-class-version-of-a-function –  Mar 21 '12 at 17:18
  • See also: http://stackoverflow.com/questions/232030/c-parent-class-calling-a-child-virtual-function –  Mar 21 '12 at 17:18
  • See also: http://stackoverflow.com/questions/1580779/call-pure-virtual-function-from-parent-class –  Mar 21 '12 at 17:19
  • See also: http://stackoverflow.com/questions/1498766/c-call-virtual-method-in-child-class –  Mar 21 '12 at 17:21
  • possible duplicate of [What is the slicing problem in C++?](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c) – R. Martinho Fernandes Mar 22 '12 at 10:22

1 Answers1

7

In order to do this you need to make the Parent declaration a pointer or a reference.

Parent* obj = new Son();

In it's current form your declaring obj to be an instance of Parent. This means the assignment from Son() doesn't create a reference to a Son instance, instead it slices the object into a Parent value.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • And what if I wanted to contain a list of objects in say an stl vector? Would that require a vector of pointers? – slayton Mar 21 '12 at 16:11
  • 1
    @slayton Yes. That's precisely right. Though you may want to look into unique_ptr or shared_ptr for easier memory management. – Agentlien Mar 21 '12 at 16:13