Object Inheritance

I have to debug/add code to this incomplete program. I implemented it as given, and no errors pop up so I have no idea what's wrong. I have already went through tutorials about inheritance and polymorphism. I believe it has to do something with B's constructor referencing an A function. Can someone please help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>

using namespace std;


Class A {
public:
  virtual void doSomething() { 
    cout<<"A did something. \n";
  }

  //Something is missing here...

}

Class B : public A {
  explicit B(const string & myString) : myValue(myString) {
  }

  virtual void doSomething() {
    cout<<"B did something. "<<myString<<"\n";
  }

private:
  string myString;
}

int main () {
  A * myPointer = new B("String value");
  myPointer->doSomething();
  delete myPointer;

  return 0;
}




B did something. String value
Last edited on
I implemented it as given, and no errors pop up so I have no idea what it's missing

I have no idea what's missing either. What are you supposed to be doing in the first place?
it just says, "Insert the missing code."
Last edited on
I see what it's missing.

Notice how you're deleting 'myPointer' polymorphically. That is... it's a A pointer, but it points to a B object.

As the code is written now... you will be leaking memory due to the missing code.
Thank you! I really would have never guessed. After some researching the topic, it looks like this might be what they are looking for.

http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors

Yep, I think you hit the nail on the head. Good work.
Topic archived. No new replies allowed.